我如何访问参数.在自定义的小枝扩展内的Yml内容


How can I access to parameters.yml content within a custom twig extension

如何访问参数。在自定义的小枝扩展内的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';
    }
}

您可以在注册扩展时注入容器或单个参数- 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';
    }
}

排序:

我正在传递全局Symfony代码从控制器:

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

创建URL:

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