Miloš - 11 months ago 197

Twig Question

I have a division in twig. Sometimes, the result can be with decimals and i need to have always a rounded up result.

Ex.

`7 / 2 = 3.5`

I would like to have

`7 / 2 = 4`

I know how to use floor in twig:

`7 / 2 | floor = 3`

But this is rounding to the down digit, not to the upper one.

I know also that i can use number_format

`7 / 2 | number_format(0, '.', ',') = 3`

So this will also take the down digit.

Any idea on how to tell twig to take the upper digit ?

This can be done in a controller (Symfony), but I am looking for the twig version.

Thank you.

Answer

You can extend twig and write your custom functions as it is described here

And it will be something like this:

```
<?php
// src/Acme/DemoBundle/Twig/AcmeExtension.php
namespace Acme\DemoBundle\Twig;
class AcmeExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
'ceil' => new \Twig_Filter_Method($this, 'ceil'),
);
}
public function ceil($number)
{
return ceil($number);
}
public function getName()
{
return 'acme_extension';
}
}
```

So you can you use it in twig:

```
7 / 2 | ceil
```

Source (Stackoverflow)