How to access the _context variable in a macro in TWIG?

I am trying to access one of the branch variables in a macro. I know that I can not do this directly.

as with PHP functions, macros do not have access to the current template variables

but the same page state:

You can pass the entire context as an argument using the special _context variable.

What is the syntax for passing _context to a macro and for accessing it in a macro?

thanks

+7
macros php twig
source share
2 answers

Consider the following example:

1) Create a variable in the current context

{% set x = 42 %} 

2) Declare a macro that takes an object as a parameter

 {% macro test(variables) %} variable x = {{ variables.x | default('undefined') }} {% endmacro %} 

3) Call your macro with a special _context object

 {{ _self.test(_context) }} 

This will display:

variable x = 42

+11
source share

You can also use the varargs property of the macro (convenient if you do not want to specify a parameter in the macro):

  • I assume that you have several twig vars specified in your template.

      {%set bodyType = "skinny" %} 
  • With any twig macro, you pass _context as the last argument .

      {{ _self.MyAmazaingMacroThatDoesEverything("french fries",_context) 
  • in the macro:

      {% macro MyAmazaingMacroThatDoesEverything(healthyFood) %} variable yourTwigPageVar = {{ varargs[0].bodyType | default('undefined') }} <h1>I like {{healthyFood}}, eating them that makes me {{yourTwigPageVar}}</h2> {% endmacro %} 
+1
source share

All Articles