简体   繁体   中英

Symfony2 Twig overriding default path function

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM