rck6982 rck6982 - 3 months ago 20
Twig Question

Use filter inside another filter twig in symfony2

I need to know how can I get a filter from another filter, I have the next code. Maybe I have to use Twig_Enviroment, but I don't how.

The Idea is:


  • The filter A converts a number in words. This is done.

  • The filter B should use filter A to convert a currency value to words.

    class CurrencyToWordsExtension extends \Twig_Extension
    {
    public function getFilters()
    {
    return array(
    new \Twig_SimpleFilter('currencyToWords', array($this, 'currencyToWordsFilter'))
    );
    }

    function currencyToWordsFilter($number)
    {
    // $toWords = $env->getFilter('toWords');
    $number = number_format((float)$number, 2);
    $pesos = floor($number);
    $centavos = ($number - $pesos) * 100;

    return $pesos .' con '. $centavos;

    }

    public function getName()
    {
    return 'currencyToWords';
    }


    }


Answer

There are a lot of possibilities:

  • Move out logic from filters to separate classes. Filters should be light wrappers of complicated logic.
  • Move both of filters in the same Twig Extension class (if they are simple and both are your code). Then you can call internal class method.
  • Inject dependencies into Twig Extension class constructor in services.yml

services.yml

services:
    twig.currency_extension:
        class: AppBundle\Twig\CurrencyExtension
        public: false
        arguments: [ '@twig.words_extension' ]
        tags:
            - { name: twig.extension }

CurrencyExtension.php

class CurreycExtension extends Twig_Extension
{
    /** @var WordsExtension */
    private $wordsExtension;

    public __construct(WordsExtension $wordsExtension)
    {
        $this->wordsExtension = $wordsExtension
    }

    //...
}

Also try naming filters according to twig conventions: snake_case, short.