我正试图访问宏中的一个trick变量。我知道我不能直接这么做。
与PHP函数一样,宏不能访问当前的模板变量
但页面状态相同:
可以使用特殊的_context变量将整个上下文作为参数传递。
将_context传递到宏以及在宏中访问它的语法是什么?
感谢
考虑以下示例:
1) 在当前上下文中创建变量
{% set x = 42 %}
2) 声明一个将对象作为参数的宏
{% macro test(variables) %}
variable x = {{ variables.x | default('undefined') }}
{% endmacro %}
3) 使用特殊的_context
对象调用宏
{{ _self.test(_context) }}
这将显示:
变量x=42
您也可以使用宏的varargs属性(如果您不想在宏中规定参数,则为handy):
-
我想你的模板中已经规定了一些小变化。
{%set bodyType = "skinny" %}
-
对于任何分支宏,您都会将_context作为最终参数传入。
{{ _self.MyAmazaingMacroThatDoesEverything("french fries",_context)
-
在宏中:
{% macro MyAmazaingMacroThatDoesEverything(healthyFood) %} variable yourTwigPageVar = {{ varargs[0].bodyType | default('undefined') }} <h1>I like {{healthyFood}}, eating them that makes me {{yourTwigPageVar}}</h2> {% endmacro %}