Or, just create the twig extension:
ByteConversionTwigExtension.php
<?php
// src/AppBundle/Twig/Extension
namespace AppBundle\Twig\Extension;
class ByteConversionTwigExtension extends \Twig_Extension
{
/**
* Gets filters
*
* @return array
*/
public function getFilters()
{
return array(
new \Twig_SimpleFilter('format_bytes', array($this, 'formatBytes')),
);
}
public function getName()
{
return 'format_bytes';
}
function formatBytes($bytes, $precision = 2)
{
$units = array('B', 'KiB', 'MiB', 'GiB', 'TiB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
// Uncomment one of the following alternatives
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
}
services.yml
parameters:
app.byte_conversion_twig_extension.twig.extension.class: AppBundle\Twig\Extension\ByteConversionTwigExtension
services:
app.byte_conversion.twig.extension:
class: %app.byte_conversion_twig_extension.twig.extension.class%
tags:
- { name: twig.extension }
Twig template:
{{ variable | format_bytes }}