Symfony2 Twig overriding default path function

前端 未结 1 538
滥情空心
滥情空心 2020-12-07 02:47

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.

Th

相关标签:
1条回答
  • 2020-12-07 03:13

    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.

    0 讨论(0)
提交回复
热议问题