簡體   English   中英

Twig中的遞歸宏

[英]Recursive macro in Twig

我已經為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.

如果我將_self導入為x,那么當我最初調用宏時它會起作用:

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

但我不能使用_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>

它是用Twig的文檔編寫的:

Twig宏無法訪問當前模板變量

您還必須在模板中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() }}

或者您可以將導入的_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