如何访问 TWIG 宏中的模板变量? [英] How can I access template variable in TWIG macro?
问题描述
我无法访问 TWIG 宏中的模板变量.
这是一个简化的例子:
{% set myname = "Ligio" %}{{ _self.pagedurl(1) }}{% 宏 pagedurl(page) %}嗨 {{ _self.myname }}!这是页码 {{ page }}{% endmacro %}
如何在不将变量 myname 传递给宏的情况下访问它?
你不能.
如文档中所述:
<块引用>作为 PHP 函数,宏无法访问当前模板变量.
您唯一的解决方案是将参数传递给宏
:
{% import _self as flow %}{{ flow.pagedurl(1, "Ligio") }}{% 宏 pagedurl(page, myname) %}我是 }}!这是页码 {{ page }}{% endmacro %}
重要提示:
您可能已经注意到,在我的示例中,我调用 {% import _self as flow %}
.
这是您必须做的事情:
当您在要使用它的模板中定义宏时,您可能很想通过 _self.input() 直接调用宏而不是导入它;即使看起来有效,这只是一个当前实现的副作用,它将不再适用树枝 2.x.
http://twig.sensiolabs.org/doc/tags/macro.htmlp>
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?
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
这篇关于如何访问 TWIG 宏中的模板变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!