Symfony 2.8
# AppBundle\Twig\AppExtension.php
<?php
namespace AppBundle\Twig;
class AppExtension extends \Twig_Extension
{
/**
* This is where one defines the filters one would to use in their twig
* templates
*
* @return Array
*/
public function getFilters()
{
return array(
new \Twig_SimpleFilter('shortNumber', array($this, 'shortNumber')),
);
}
/**
* Shorten the number
*
* @param integer
* @return string
*/
public function shortNumber($number)
{
$k = pow(10,3);
$mil = pow(10,6);
$bil = pow(10,9);
if ($number >= $bil)
return number_format((float)$number / $bil, 1, '.', '').'Billion';
else if ($number >= $mil)
return number_format((float)$number / $mil, 1, '.', '').'M';
else if ($number >= $k)
return number_format((float)$number / $k, 1, '.', '').'K';
else
return (int) $number;
}
/**
* Get name
*/
public function getName()
{
return 'app_extension';
}
}
Add your extension to services.yml
# app/config/services.yml
services:
app.twig_extension:
class: AppBundle\Twig\AppExtension
public: false
tags:
- { name: twig.extension }
Use it in TWIG
<span>{{ number|shortNumber }}</span>
e.g.
<span>{{ 1234|shortNumber }}</span> -> <span>1.2k</span>