How to register filters (formerly helpers) in Latte?
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);
}
}
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.