Home » Php » php – How to register filters (formerly helpers) in Latte?

php – How to register filters (formerly helpers) in Latte?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

<?php
    $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.

How to&Answers:

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);
    }
}

Answer:

In presenter, there is instance of Latte\Engine available in $this->template so everything you have to do is register filter like this:

<?php
    abstract class BasePresenter extends Nette\Application\UI\Presenter
    {
        public function beforeRender()
        {
            // register filters
            $this->template->addFilter('myFilter', function ($s) {
                // don't forget to set your own magic
                return someMagic($s);
            });
        }

    }
?>

I postend an example using BasePresenter which is parent of all others presenters but you can register it only in presenter you want to and speed up your application.

Answer:

In addition to @Nortys answer.

Sometimes it’s usefull to inject some data from Presenter into anonymous function:

<?php
abstract class BasePresenter extends Nette\Application\UI\Presenter
{
    public function beforeRender()
    {
        $locale = 'en';

        // register filters
        $this->template->addFilter('myFilter', function ($s) use ($locale) {
            // don't forget to set your own magic
            return someMagic($s, $locale);
        });
    }
}
?>