How can I access template variable in TWIG macro?
Solution 1
You can not.
As stated in the documentation:
As PHP functions, macros don't have access to the current template variables.
Your only solution is to pass the parameter to the macro
:
{% import _self as flow %}
{{ flow.pagedurl(1, "Ligio") }}
{% macro pagedurl(page, myname) %}
Hi {{ myname }}! This is Page Num {{ page }}
{% endmacro %}
IMPORTANT NOTE:
You may have noticed in my example, I call {% import _self as flow %}
.
This is something you MUST do:
When you define a macro in the template where you are going to use it, you might be tempted to call the macro directly via _self.input() instead of importing it; even if seems to work, this is just a side-effect of the current implementation and it won't work anymore in Twig 2.x.
http://twig.sensiolabs.org/doc/tags/macro.html
Solution 2
If you need to pass more than one global variable into the macro, you might find the _context
variable useful:
{% macro mymacro(globalvars) %}
Value of the global variable pi is {{ globalvars.pi }}
{% endmacro %}
{% set pi = 3.14159 %}
{{ _self.mymacro(_context) }}
Solution 3
You can set a global variable and access it anywhere in the template
$loader = new \Twig_Loader_Filesystem('path/to/templates');
$twig = new \Twig_Environment($loader);
$twig->addGlobal('V_Name', 'V_Value');
Related videos on Youtube
Ligio
Updated on September 27, 2022Comments
-
Ligio over 1 year
I'm not able to access template variable in TWIG macro.
Here is a simplified example:
{% set myname = "Ligio" %} {{ _self.pagedurl(1) }} {% macro pagedurl(page) %} Hi {{ _self.myname }}! This is Page Num {{ page }} {% endmacro %}
How can I access the variable myname without passing it to the macro?
-
Maerlyn about 11 yearsDid you try a simple
{{ myname }}
? -
Ligio about 11 yearswith {{ myname }} I'm not in the scope of the variable... It's not working!
-
-
David Lundquist over 6 yearsOne solution that can "hack" your "globals" is to build a twig var (or use _context) as an array of your important variables and then pass this single twig var as the last argument to any macro you use. --------- When within the scope of your macro you can then access this final argument via the varargs property. for example: {% set MyGlobals = varargs[0] %}
-
Loenix about 3 yearsIt seems with Twig 3.x we don't need to import _self and you should not.
-
thaikolja about 3 yearsThanks, this is indeed the best solution when working with Timber/Twig/WordPress.
-
Benoit Duffez almost 3 yearsThe documentation justification seems ridiculous. PHP functions may have access to global variables, and PHP methods have access to class members. They could just stay it's by design instead of trying to blame it on PHP.