简体   繁体   English

Twig中的递归宏

[英]Recursive macro in Twig

I've added a macro to Twig and I'm trying to get that Macro to call itself. 我已经为Twig添加了一个宏,我试图让宏调用自己。 It appears that using _self appears to now be frowned on and doesn't work, returning the error: 似乎使用_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.

If I do import _self as x, then it works when I initially call the macro: 如果我将_self导入为x,那么当我最初调用宏时它会起作用:

{% import _self as twigdebug %}
{{ twigdebug.recursiveTree() }}

But I can't then call the macro recursively using _self or twigdebug.recursiveTree. 但我不能使用_self或twigdebug.recursiveTree递归调用宏。

Is there a way to do this? 有没有办法做到这一点?

Example: 例:

{% 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>

It is written in Twig's macro documentation: 它是用Twig的文档编写的:

Twig macros don't have access to the current template variables Twig宏无法访问当前模板变量

You either have to import self in template AND in the macro as well: 您还必须在模板中import self并在宏中import

{% 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() }}

Or you can pass the imported _self object directly to the macro. 或者您可以将导入的_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) }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM