Twig: [2.0] Accessing Twig_Template attributes is forbidden exception

# macros.html.twig
{% macro error_main_error(message) %}
    <b>{{ message }}</b>
{% endmacro %}
# template.html.twig
{% import "macros.html.twig" as macro_helper %}

{{ macro_helper.error_main_error("Some message") }}

Triggers the following exception

(Twig_Error_Runtime(code: 0): Accessing Twig_Template attributes is forbidden.

Is this not possible anymore in 2.x?

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 6
  • Comments: 28 (17 by maintainers)

Commits related to this issue

Most upvoted comments

@goetas Macros are indeed the darkest aspect of Twig and we know that the current situation is far from being ideal. Sorry that yo experienced it the hard way.

The body of an {% embed %} block is a separate template, so its imports are separate (as are its block definitions). So you should import the macro inside the nested template: https://twigfiddle.com/91rlep/15

@tlorens: I’ve updated the answer for extends: http://stackoverflow.com/a/41590052/1668200

First, and as shown in Twig Fiddle now, you should fix all deprecations before upgrading to Twig 2.0. That’s explained in the deprecated document (first item).

I’ve also just added a small section about macros to describe this specific issue (see c9a14464).

Done. It doesn’t make lots of sense on large screens but doesn’t disturb anyway.

@fabpot we seems to have an issue regarding the location of errors if they end up on the extends tag. Aren’t we providing the error location directly in the error almost everywhere now ? Then why would we put it there ?

the parent can even change dynamically at runtime

remember that. then makes sense importing macros explicitly. just my “upgrade” experience was a bit traumatic 😃

Alright, everything clear. Now I have to decide if “refactoring” all the templates of my app, or forcing it to twig 1.x.

Thanks

Yes, my case is very similar to @Findus23 , i’m using template inheritance

https://twigfiddle.com/91rlep/5 2.0 not working

https://twigfiddle.com/91rlep/6 1.30 working

( @stof did not know about twigfiddle.com, sorry if the first issue description was not accurate)