Search code examples
symfonytwigslug

Use Twig Extension in controller


I have a slugify method in an Twig Extension which i would like to use in some cases in a controller, f.e with redirects.
Is there an easy way for this?
How could i access functions from Twig Extensions in the controller?

Or do i have to make the slugify method somewere as a helper in order to use it in the code and in twig?


Solution

  • I would advise creating a general service and injecting it to the Twig extension. The extension would act just as a wrapper to the service.

    namespace Acme\Bundle\DemoBundle\...;
    
    class MyService
    {
        public function myFunc($foo, $bar)
        {
            // some code...
        }
    
        // additional methods...
    }
    

    EDIT - as mentioned by Squazic, the first argument must implement Twig_ExtensionInterface. An inelegant solution would be to add methods to MyTwigExtension, that in turn call out respective methods in the service.

    namespace Acme\Bundle\DemoBundle\Twig\Extension;
    
    class MyTwigExtension extends \Twig_Extension
    {
        protected $service;
    
        public function __construct(MyService $service)
        {
            $this->service = $service;
        }
    
        public function getFunctions()
        {
            return array(
                'myTwigFunction' => new \Twig_Function_Method($this, 'myFunc'),
                'mySecondFunc'   => new \Twig_Function_Method($this, 'mySecondFunc'),
            );
        }
    
        public function myFunc($foo, $bar)
        {
            return $this->service->myFunc($foo, $bar);
        }
    
        // etc...
    
    }