How to create a macro that convert bytes to KB, MB, GB etc
Question
I have a video in my page and we can download it, next to the download link I have a number that shows the size of the video.
Now I have it in bytes, and I want to convert it in KB, MB or GB. From what I understood the best way of doing that is with a macro.
{% macro downloadSize(bytes) %}
{% spaceless %}
{% set bytes = x/1024 %}
{% if bytes < 1024 %}
KB
{% endif %}
...
{% endspaceless %}
{% endmacro %}
I know I dont have much, but I really need help on the syntax and how to acomplish this. I want my final value to be like " 12.2 MB "
Solution
As @Flukey mentioned, the way is to create an extension.
I've done that as an exercise. Just go to
https://github.com/BrazilianFriendsOfSymfony/BFOSTwigExtensionsBundle
and get the extension.
OTHER TIPS
And old question, but for anyone else -> if for any reason you don't want to meddle with TwigExtensions here is how that macro would look like:
{% macro bytesToSize(bytes) %}
{% spaceless %}
{% set kilobyte = 1000 %}
{% set megabyte = kilobyte * 1000 %}
{% set gigabyte = megabyte * 1000 %}
{% set terabyte = gigabyte * 1000 %}
{% set petabyte = terabyte * 1000 %}
{% if bytes < kilobyte %}
{{ bytes ~ ' B' }}
{% elseif bytes < megabyte %}
{{ (bytes / kilobyte)|number_format(2, '.') ~ ' KB' }}
{% elseif bytes < gigabyte %}
{{ (bytes / megabyte)|number_format(2, '.') ~ ' MB' }}
{% elseif bytes < terabyte %}
{{ (bytes / gigabyte)|number_format(2, '.') ~ ' GB' }}
{% elseif bytes < petabyte %}
{{ (bytes / terabyte)|number_format(2, '.') ~ ' TB' }}
{% else %}
{{ (bytes / petabyte)|number_format(2, '.') ~ ' PB' }}
{% endif %}
{% endspaceless %}
{% endmacro %}
EDIT: modified the script to match decimal measurement (KB, MB, GB..) instead of binary (KiB, MiB, GiB...).