Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access template variable in TWIG macro?

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?

like image 747
Ligio Avatar asked Feb 27 '13 08:02

Ligio


3 Answers

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

like image 134
cheesemacfly Avatar answered Oct 12 '22 00:10

cheesemacfly


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) }}

Ref: this or this answer.

like image 36
Czechnology Avatar answered Oct 12 '22 00:10

Czechnology


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');
like image 2
Mohamad Hamouday Avatar answered Oct 11 '22 22:10

Mohamad Hamouday