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?
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 thetwig.extensiontag. And finally you need to implement thegetFunctions()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.