Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Twig overriding default path function

Tags:

php

twig

symfony

I need a way to override the basic path() function in twig.

I have a twig extension already, but defining a path filter there did not do the trick for me.

Thanks in advance.

like image 477
ZeeCoder Avatar asked May 30 '14 15:05

ZeeCoder


1 Answers

Extend the default routing extension class.

use Symfony\Bridge\Twig\Extension\RoutingExtension;

class MyRoutingExtension extends RoutingExtension
{
    public function getPath($name, $parameters = array(), $relative = false)
    {
        //some code
    }
}

Then specify your class using a parameter:

parameters:
    twig.extension.routing.class: MyNamespace\MyRoutingExtension

======================================================================

To inject more dependencies such as the domain you basically need to copy the service definition and then add your stuff:

# services.yml
twig.extension.routing:
    class: '%twig.extension.routing.class%'
    public: false
    arguments: 
      - '@router'
      - 'domain'

class MyRoutingExtension extends RoutingExtension
{
    protected $domain;

    public function __construct($router,$domain)
    {
        parent::__construct($router);

        $this->domain = $domain;
    }
}

You could also add the argument to the service definition from inside of your DependencyInjection extension. That might be a bit more robust that copying the service definition. There is always the risk that the definition might change if symfony is updated. Unlikely. I don't happen to have an example handy.

By the way, you should probably avoid adding a question to an existing question. Some of the down voters will take a dim view.

like image 173
Cerad Avatar answered Nov 08 '22 11:11

Cerad