Symfony2 Twig 覆盖默认路径功能 [英] Symfony2 Twig overriding default path function

查看:33
本文介绍了Symfony2 Twig 覆盖默认路径功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种方法来覆盖 twig 中的基本 path() 函数.

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.

提前致谢.

推荐答案

扩展默认路由扩展类.

use SymfonyBridgeTwigExtensionRoutingExtension;

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: MyNamespaceMyRoutingExtension

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

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

要注入更多依赖项,例如域,您基本上需要复制服务定义,然后添加您的内容:

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;
    }
}

您还可以从 DependencyInjection 扩展的内部将参数添加到服务定义中.这可能比复制服务定义更健壮.如果 symfony 更新,定义可能会改变的风险总是存在的.不太可能.我没有手头的例子.

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.

这篇关于Symfony2 Twig 覆盖默认路径功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆