简体   繁体   English

Twig 2.0错误消息“禁止访问Twig_Template属性”

[英]Twig 2.0 error message “Accessing Twig_Template attributes is forbidden”

Since upgrading to Twig 2.0 I get the error message Accessing Twig_Template attributes is forbidden . 自升级到Twig 2.0后,我收到错误消息, Accessing Twig_Template attributes is forbidden The referred line contains either an {{ include }} or a macro call. 引用的行包含{{ include }}或宏调用。

In Twig 2.0 {{ import }} 'ed macros are not inherited to child templates anymore, see https://github.com/twigphp/Twig/issues/2336 在Twig 2.0中{{ import }} 'ed宏不再继承到子模板,请参阅https://github.com/twigphp/Twig/issues/2336

Solution: You need to import the required macro(s) in every single .twig file. 解决方案: 您需要在每个.twig文件中导入所需的宏。

If the error is showing up on a line containing {{ include }} or {{ extends }} , you have to look into the template that's being included/extended, and import the macro there. 如果错误显示在包含{{ include }}{{ extends }} ,则必须查看正在包含/扩展的模板,并在那里导入宏。

If you have a lot of Twig files using your macros, it might be easier and less error-prone to define global Twig Functions through a Twig Extension . 如果您使用宏有很多Twig文件,通过Twig扩展 定义全局Twig函数可能更容易且更不容易出错。 This way you don't need to import the macros in every file (which will probably be fixed in a future Twig version). 这样您就不需要在每个文件中导入宏(这可能会在将来的Twig版本中修复)。

For instance, when I had 例如,当我有

{% macro error(message, dismissible=true) %}
   {# Error display code #}
{% endmacro %}

I now have defined in a Twig Extension called UtilitiesExtension the following Function : 我现在在一个名为UtilitiesExtension的Twig Extension中定义了以下函数:

    public function getFunctions()
    {
        return array(
            // ...
            new \Twig_SimpleFunction('error', array($this, 'error')),
        );
    }

    public function error($message, $dismissible = true) {
        return $this->twig->render('patterns/utils/error.html.twig', [
            'text' => $message,
            'limit' => $dismissible,
        ]);
    }

You then need to replace your macro calls with the function names; 然后,您需要使用函数名称替换宏调用; note that you cannot use dots in function names. 请注意,您不能在函数名称中使用点。

This solution is clean as Twig Macros are supposed to be the equivalent of PHP Functions. 这个解决方案很简洁,因为Twig宏应该等同于PHP函数。 Of course this should be adapted to your needs. 当然,这应该适应您的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM