I need to add custom filter for Twig in Silex framework. For example, I want apply this function to some variable:
public function addExclamation($text) {
return $text.'!!!';
}
And in twig-template do something like this:
{{ text|exclam }}
After reading http://twig.sensiolabs.org/doc/advanced.html I create "Project_Twig_Extension.php":
class Project_Twig_Extension extends Twig_Extension
{
public function getName()
{
return 'project';
}
public function getFilters()
{
return array(
new Twig_SimpleFilter('exclam', 'addExclamation'),
);
}
public function addExclamation($text) {
return $text.'!!!';
}
}
But I can't undersand where I need to put this file and how I can register this filter in "index.php" of Silex.
Can you give me step-by-step guide? Method, described at Twig addFilter using Silex? don't work.
You can add custom filters like this:
$app['twig'] = $app->share($app->extend('twig', function(\Twig_Environment $twig) {
$twig->addFilter(new Twig_SimpleFilter('exclaim', function ($value) {
return $value.'!!!';
}));
return $twig;
}));
Reference: http://silex.sensiolabs.org/doc/providers/twig.html#customization
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With