我已经为Twig添加了一个宏,我试图让宏调用自己.似乎使用_self现在似乎不赞成并且不起作用,返回错误:
using the dot notation on an instance of Twig_Template is deprecated since version 1.28 and won't be supported anymore in 2.0.
Run Code Online (Sandbox Code Playgroud)
如果我将_self导入为x,那么当我最初调用宏时它会起作用:
{% import _self as twigdebug %}
{{ twigdebug.recursiveTree() }}
Run Code Online (Sandbox Code Playgroud)
但我不能使用_self或twigdebug.recursiveTree递归调用宏.
有没有办法做到这一点?
例:
{% macro recursiveCategory(category) %}
{% import _self as self %}
<li>
<h4><a href="{{ path(category.route, category.routeParams) }}">{{ category }}</a></h4>
{% if category.children|length %}
<ul>
{% for child in category.children %}
{{ self.recursiveCategory(child) }}
{% endfor %}
</ul>
{% endif %}
</li>
{% endmacro %}
{% from _self import recursiveCategory %}
<div id="categories">
<ul>
{% for category in categories %}
{{ recursiveCategory(category) }}
{% endfor %}
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
Twig的宏文档中是这么写的:
Twig 宏无权访问当前模板变量
您要么必须import在模板中使用 self,要么在宏中使用 self:
{% macro recursiveTree() %}
{# ... #}
{# Import and call from macro scope #}
{% import _self as twigdebug %}
{{ twigdebug.recursiveTree() }}
{% endmacro %}
{# Import and call from template scope #}
{% import _self as twigdebug %}
{{ twigdebug.recursiveTree() }}
Run Code Online (Sandbox Code Playgroud)
或者您可以将导入的_self对象直接传递给宏。
{% macro recursiveTree(twigdebug) %}
{# ... #}
{# Call from macro parameter #}
{# and add the parameter to the recursive call #}
{{ twigdebug.recursiveTree(twigdebug) }}
{% endmacro %}
{# Import and call from template scope #}
{% import _self as twigdebug %}
{{ twigdebug.recursiveTree(twigdebug) }}
Run Code Online (Sandbox Code Playgroud)