简体   繁体   中英

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 . The referred line contains either an {{ include }} or a macro call.

In Twig 2.0 {{ import }} 'ed macros are not inherited to child templates anymore, see https://github.com/twigphp/Twig/issues/2336

Solution: You need to import the required macro(s) in every single .twig file.

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.

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 . This way you don't need to import the macros in every file (which will probably be fixed in a future Twig version).

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 :

    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. Of course this should be adapted to your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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