phpnette

How to register filters (formerly helpers) in Latte?


I would like to create my own filter for Latte templating engine. There is an example in their documentation but it doesn't describe how to register it inside presenter.


$latte = new Latte\Engine;
$latte->addFilter('myFilter', function ($s) {
    return someMagic($s)
});

I bet there will be simple way to get instance of Latte\Engine inside presenter but I'm not sure how.


Solution

  • Filters can be registered through config.neon too.

    services:
        nette.latteFactory:
            setup:
                - addFilter(abs, @App\Latte\AbsFilter)
    
        - App\Latte\AbsFilter
    

    Filter class can look like this:

    namespace App\Latte;
    
    class AbsFilter extends \Nette\Object
    {
        /**
         * @param int $number
         * @return int
         */
        public function __invoke($number)
        {
            return abs($number);
        }
    }