php - Symfony2 将变量从自己的包传递到 Twig

标签 php symfony twig

我正在开发第三方包。

我需要定义一个可以在这个包的 Twig 模板中使用的变量。

当尝试在我的 bundle config.yml 模式中声明时,在我的项目中变量步进 twig 模板,

twig:
    globals:
        test_vars: %test_vars%

我收到这个错误。

InvalidArgumentException in YamlFileLoader.php line 357:
There is no extension able to load the configuration for "twig" (in /home/domain.ext/vendor/test/test-bundle/test/TestBundle/DependencyInjection/../Resources/config/.yml). Looked for namespace "twig", found none

非常感谢


解决方案代码,感谢@alexander.polomodov 和@mblaettermann

GlobalsExtension.php

namespace Vendor\MyBundle\Twig\Extension;

class GlobalsExtension extends \Twig_Extension {

    public function __construct($parameter) {
        $this->parameter= $parameter;
        //...
    }

    public function getGlobals() {

        return array(
            'parameter' => $this->parameter
            //...
        );
    }

    public function getName() {
        return 'MyBundle:GlobalsExtension';
    }
}

我的.yml

services:
    twig.extension.globals_extension:
        class: Vendor\MyBundle\Twig\Extension\GlobalsExtension
        arguments: [%my.var%]
        tags:
            - { name: twig.extension }

我的.html.twig

my parameter: {{ parameter }}

最佳答案

您应该使用依赖注入(inject)在您自己的包中完全实现此逻辑。这意味着,不要劫持 twig: 配置键,而是使用你自己的 bundle 配置键。

在你的捆绑容器扩展中,你可以将你的配置值传递到容器参数中,然后将这些参数作为构造函数参数传递给 Twig 扩展。

但是,正如 Alex 已经指出的那样,在将 Twig Extension 添加到容器之前,您需要检查 Twig Bundle 是否已加载且可用。

http://symfony.com/doc/current/cookbook/templating/twig_extension.html

关于php - Symfony2 将变量从自己的包传递到 Twig ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36000326/

相关文章:

php - 如何从给定的日期范围内找到确切的季节和日期?

php - 如何从命令的 "php artisan list"隐藏默认 artisan 命令?

symfony - 创建一个简单的表单

php - 正在准备语句,但未执行

Symfony2 在 Twig 中获取用户角色

php - 如何在帖子中上传数百张图片?

php - 如果存在更新,否则插入一个查询

php - 了解双向关系中拥有方如何运作

symfony - 如何制作 symfony2 表单以在表单类型中自动输入当前登录用户的 ID?

twig - 如何使用 twig 获取 craft 中的父页面标题?