1
votes

I'm trying to create a new twig filter. I'm confused by this tutorial: https://twig.symfony.com/doc/2.x/advanced.html#filters

I don't know where should I put the code (which file, which path)...

I created a file called SnipText.php

<?     
$filter = new Twig_Filter('snip', function ($context, $texto) {
    $textoArr = explode(" ", preg_replace('/<[^>]*>/', '', $texto));
    $qtdWords = count($textoArr);
    $texto = '';
    for($i=0;$i<40;$i++){
        if($qtdWords > $i)
            $texto .= $textoArr[$i] . ' ';
        }
    $texto .= '...';
    return $texto;
}, array('needs_context' => true));

$twig = new Twig_Environment($loader);
$twig->addFilter($filter);
?>

And then I put it on my src folder. Twig is in my vendor folder. I get the error:

Fatal error: Uncaught Twig_Error_Syntax: Unknown "snip" filter.

Can someone show me step by step on how to create a filter on twig?

2
Are you using the Symfony framework or just some sort of stand alone app which happens to use twig?Cerad
The second option I guess, I started working on the project after the first dev left and I've never worked with Twig beforeFlávia Nunes
Okay. You need to figure out where new Twig_Enviroment() is called. Should be some sort of bootstrap file or something. And then add your filter. I expect that you will probably find other filters being defined so it should be easy enough to figure out where code goes. If the project you inherited did not use twig then you need to step back and work through the getting started docs. And make sure you are using the correct doc version. If the project is more than a couple of years old then it might be using Twig 1 vs Twig 2. Big difference.Cerad
You are creating another instance of twig and adding your filter to that instance rather than to the instance you are rendering your templates with.DarkBee
Thank you guys, I found where the Twig_Enviroment() is called :DFlávia Nunes

2 Answers

1
votes

When you work with symfony you should take a look at the symfony documentation how to define a twig filter / extension.

https://symfony.com/doc/current/templating/twig_extension.html

First you have to put your new class in a new namespace (App/Twig in the tutorial) and register your class as service and tag it with the twig.runtime tag. Then it's loaded automatically and you can use it.

1
votes

The comment by @Cerad helped me a lot! Thank you

Okay. You need to figure out where new Twig_Enviroment() is called. Should be some sort of bootstrap file or something. And then add your filter. I expect that you will probably find other filters being defined so it should be easy enough to figure out where code goes. If the project you inherited did not use twig then you need to step back and work through the getting started docs. And make sure you are using the correct doc version. If the project is more than a couple of years old then it might be using Twig 1 vs Twig 2. Big difference. – Cerad