Reputation: 14052
i want to use the php stripslashes function inside a twig template but this function is not a standard twig function, so i have to add it to twig as an extension, i tried this code inside a controller, but it doesnt work:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class XController extends Controller
{
public function YAction($page)
{
$twig=$this->get('twig');
$twig->addFunction('functionName', new Twig_Function_Function('someFunction'));
...
do i need a use statement for the "Twig_Function_Function" class? am i doing this wrong?
Upvotes: 1
Views: 4368
Reputation: 688
Or {{ function('stripslashes', "This\\'ll do") }}
(or apply stripslashes() when building your Twig context)
But, also, if you do this in php:
add_filter('timber/twig', function(\Twig_Environment $twig) {
$twig->addFunction(new Twig\TwigFunction('stripslashes', 'stripslashes'));
return $twig;
});
Then this works in twig:
{{ stripslashes("This\'ll do...") }}
Upvotes: 1
Reputation: 13891
If you want to use it in your twig templates, you don't need to make any add or call inside your controller, Read the How to write a custom Twig Extension section of the documentation.
Basicaly, you need to create an Extension Class that extends \Twig_Extension
, then you need to register it as a service using the twig.extension
tag. And finally you need to implement the getFunctions()
method in order to add customized twig functions.
But in your case better is to add a filter, with the same logic you can also add a getFilters()
method in your extension class so that you can specify your customized filters.
Also, take a deeper look at the Extending Twig section of the documentation to understand all the ways twig can be extended.
Upvotes: 4