How to register filters (previously assistants) in Latte?

I would like to create my own filter for the Latte templating engine . There is an example in their documentation, but it does not describe how to register it inside the presenter.

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

I'm sure there will be an easy way to get a Latte \ Engine instance inside the presenter, but I'm not sure how to do this.

+6
source share
3 answers

Filters can also be registered via config.neon .

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

A filter class might look like this:

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

There is a Latte\Engine instance in the presenter available in $this->template , so all you have to do is register the filter as follows:

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

Publish the example using BasePresenter , which is the parent of all other presenters, but you can only register it in the presenter you want and speed up your application.

+3
source

In addition to @Nortys answer.

It is sometimes useful to enter some data from Presenter into an 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); }); } } ?> 
+1
source

Source: https://habr.com/ru/post/977902/


All Articles