如何访问TWIG宏中的模板变量? [英] How can I access template variable in TWIG macro?

查看:238
本文介绍了如何访问TWIG宏中的模板变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法访问TWIG宏中的模板变量.

这是一个简化的示例:

{% set myname = "Ligio" %}
{{ _self.pagedurl(1) }}

{% macro pagedurl(page) %}
    Hi {{ _self.myname }}! This is Page Num {{ page }}
{% endmacro %}

如何在不将变量 myname 传递给宏的情况下访问它?

解决方案

您不能.

如文档中所述:

作为PHP函数,宏无权访问当前模板 变量.

您唯一的解决方案是将参数传递给macro:

{% import _self as flow %}
{{ flow.pagedurl(1, "Ligio") }}

{% macro pagedurl(page, myname) %}
    Hi {{ myname }}! This is Page Num {{ page }}
{% endmacro %}

重要说明:

在您的示例中,您可能已经注意到,我打电话给{% import _self as flow %}.
这是您必须要做的事情:

当您在模板中定义要使用宏的位置时, 您可能会想直接通过_self.input()调用宏 而不是导入它;即使看起来可行,但这只是一个 当前实施的副作用,它将在以下版本中不再起作用 Twig 2.x.

http://twig.sensiolabs.org/doc/tags/macro.html

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆