1

I need to get a parameter value in my following twig extension class

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

In controller we can use like this $this->container->getParameter('contact_email'); But I need the value in twig extension class.

4

1 回答 1

0

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

配置.yml

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

你的扩展名.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
}
于 2013-06-26T15:23:16.547 回答