【问题标题】:How I get the parameter value in my twig extension class of symfony2如何在 symfony2 的树枝扩展类中获取参数值
【发布时间】:2013-06-26 13:27:24
【问题描述】:

我需要在我的以下树枝扩展类中获取一个参数值

namespace xxxx\WebBundle\Twig;
use Symfony\Component\HttpKernel\KernelInterface;

class MyExtension extends \Twig_Extension

{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('affliate', array($this, 'urlFilter')),
        );
    }

    public function urlFilter($url,$aff)
    {
        $separator = "?";
        if (strpos($url,"?")!=false) {
            $separator = "&";
        }
        $parse = parse_url($url);
        //echo $parse['host'];

        $app_url = $url.$separator.'tag='.$aff;

        return $app_url;
    }

    public function getName()
    {
        return 'wishbot_extension';
    }
}

在控制器中我们可以像这样使用 $this->container->getParameter('contact_email'); 但我需要树枝扩展类中的值。

【问题讨论】:

  • 我的回答是否帮助您解决了您的问题或有什么不清楚的地方?如果是请评论,否则请接受答案:)

标签: symfony


【解决方案1】:

将参数作为参数注入到树枝扩展的构造函数中,如下所示:

config.yml

services:
    twig.extension.your_extension:
        class: Vendor\YourBundle\Twig\Extension\YourExtension
        arguments: [ %parameter1%, %parameter2% ]         
        tags:
            - { name: twig.extension }

YourExtension.php

protected $parameter1;
protected $parameter1;

public function __construct($parameter1, $parameter2)
{
    $this->parameter1 = $parameter1;
    $this->parameter2 = $parameter2;
}

// ....

public function urlFilter($url,$aff)
{
     // access the parameters using $this->parameter1
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多