symfonytwigcomposer-phpsymfony4twig-extension

Install twig/extensions on a Symfony 4 or Symfony 5 new project


I'm preparing to migrate a huge website from Symfony 3.4 to Symfony 4.4. To do this, I'm starting from a new fresh installation of Symfony 4.4, and as the intial project requires the use of Twig Extensions I try to install it on this new Symfony 4.4 project. But composer indicates Your requirements could not be resolved to an installable set of packages.

The error message is obvious, but I don't understand why this situation happens on a fresh symfony 4.4 project.

What I tried :

This worked : - I create a new Symfony symfony new --full --version=3.4 testproject that installed Symfony 3.4 and right after composer require twig/extensions => OK

I understand that dependencies conflits occur for Symfony 4.4 and more, but according to Symfony doc How to Write a custom Twig Extension no further actions are required and it should work.

What I'm missing ? Does someone faced the same problem ? Thanks


Solution

  • Finally it seems that running composer require twig/extensions is no more required to create custom Twig Extensions in Symfony 4. By default a new Symfony built with website skeleton owes a use Twig\Extension\AbstractExtension; as per required to create a twig extension like below one :

    namespace App\Twig;
    
    use Twig\Extension\AbstractExtension;
    use Twig\TwigFilter;
    
    class AppExtension extends AbstractExtension
    {
        public function getFilters()
        {
            return [
                new TwigFilter('price', [$this, 'formatPrice']),
            ];
        }
    
        public function formatPrice($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
        {
            $price = number_format($number, $decimals, $decPoint, $thousandsSep);
            $price = '$'.$price;
    
            return $price;
        }
    }