如何在自定义树枝扩展中访问parameters.yml内容

时间:2014-08-01 22:31:35

标签: php symfony

如何在自定义树枝扩展名中访问parameters.yml内容?

namespace Car\BrandBundle\Twig;

class HashExtension extends \Twig_Extension
{
    public function hash($param)
    {
        return sha1($param . $this->container->getParameter('secret'));
    }

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

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

2 个答案:

答案 0 :(得分:2)

注册时,您可以将容器或单个参数注入扩展程序 - http://symfony.com/doc/current/cookbook/templating/twig_extension.html#register-an-extension-as-a-service

services:
    acme.twig.acme_extension:
        class: Acme\DemoBundle\Twig\AcmeExtension
        arguments:
            - @service_container
        tags:
            - { name: twig.extension }

<强>更新

你以前在Symfony听过/使用过依赖注入吗?

namespace Car\BrandBundle\Twig;

use Symfony\Component\DependencyInjection\ContainerInterface;

class HashExtension extends \Twig_Extension
{
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function hash($param)
    {
        return sha1($param . $this->container->getParameter('secret'));
    }

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

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

答案 1 :(得分:0)

排序:

我将全局Symfony代码从控制器传递给twig:

return $this->render(.... `'staticCode' => $this->container->getParameter('secret'));`

使用以下方式创建网址:

<a href="{{ path('delete_process', {'hashId':brand.id|hash(staticCode) }) }}">Delete</a>

<强>扩展:

namespace Car\BrandBundle\Twig;

class HashExtension extends \Twig_Extension
{
    public function hashFilter($param, $staticCode)
    {
        return sha1($param . $staticCode);
    }

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

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

<强> services.yml

services:
    car.twig.hash_extension:
        class:  Car\BrandBundle\Twig\HashExtension
        tags:
            - { name: twig.extension }