Search code examples
stringsymfonytwigstring-math

How to make string math calculation to be calculated in Twig


I have string like "((2*160)+53)*1.00000" which I recieve in data into Twig template. How to make calculation work and return the calculed number, not the plain string of the math?

So expected output would be just one number as the result of the math (373 here).

Add: In fact the received string is "((V*160)+53)*1.00000" where V is replaced with some amount.


Solution

  • You can easily create a custom Twig function using TwigExtension (see https://symfony.com/doc/5.2/templating/twig_extension.html#create-the-extension-class).

    Like:

    <?php
    namespace App\Twig;
    
    use Twig\Extension\AbstractExtension;
    use Twig\TwigFunction;
    
    class AppExtension extends AbstractExtension
    {
        public function getFunctions()
        {
            return [
                new TwigFunction('calculate', [$this, 'calculateExpression']),
            ];
        }
    
        public function calculateExpression(string $input, array $extraValues = [])
        {
            foreach ($extraValues as $key => $value) {
                $input = str_replace($key, $value, $extraValues);
            }
    
            return eval("return $input");
        }
    }
    

    Or a kind of and used like this in Twig template:

    {{ calculate('((V*160)+53)*1.00000', {V: 53}) }}