Readable file sizes with the Twig templating system

James Dawson picture James Dawson · Mar 7, 2013 · Viewed 11k times · Source

I'm wondering if there's a built in way to output readable file sizes with the Twig templating system. Say I have something like this in my template:

<p>This limit is currently set to {{ maxBytes }}</p>

How could I format maxBytes to display something like 30 GB?

Answer

Chase picture Chase · Mar 8, 2013

There are a couple of ways you can go about accomplishing that:

1) get a Twig extension that will handle it for you. One like this one: https://github.com/BrazilianFriendsOfSymfony/BFOSTwigExtensionsBundle

Once enabled you would just do:

{{ maxBytes|bfos_format_bytes }}

And this will give you what you want.

2) You can create a macro that will do this if you dont want to add an entire extension. That would look something like this:

{% macro bytesToSize(bytes) %}
{% spaceless %}
    {% set kilobyte = 1024 %}
    {% set megabyte = kilobyte * 1024 %}
    {% set gigabyte = megabyte * 1024 %}
    {% set terabyte = gigabyte * 1024 %}

    {% if bytes < kilobyte %}
        {{ bytes ~ ' B' }}
    {% elseif bytes < megabyte %}
        {{ (bytes / kilobyte)|number_format(2, '.') ~ ' KiB' }}
    {% elseif bytes < gigabyte %}
        {{ (bytes / megabyte)|number_format(2, '.') ~ ' MiB' }}
    {% elseif bytes < terabyte %}
        {{ (bytes / gigabyte)|number_format(2, '.') ~ ' GiB' }}
    {% else %}
        {{ (bytes / terabyte)|number_format(2, '.') ~ ' TiB' }}
    {% endif %}
{% endspaceless %}
{% endmacro %}

You can read more about where to put and how to use the macros here: http://twig.sensiolabs.org/doc/tags/macro.html