Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig 2.0 error message "Accessing Twig_Template attributes is forbidden"

Tags:

php

twig

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.

like image 987
Thomas Landauer Avatar asked Jan 11 '17 11:01

Thomas Landauer


2 Answers

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.

like image 107
Thomas Landauer Avatar answered Nov 06 '22 18:11

Thomas Landauer


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 UtilitiesExtensionthe 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.

like image 43
Gounzy Avatar answered Nov 06 '22 18:11

Gounzy