Twig中的递归宏

时间:2016-11-20 18:00:57

标签: php 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递归调用宏。

有办法做到这一点吗?

2 个答案:

答案 0 :(得分:6)

示例:

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

答案 1 :(得分:3)

它是用Twig的macro文档编写的:

  

Twig宏无法访问当前模板变量

您必须在模板中使用import 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() }}

或者您可以将导入的_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) }}