Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive macro in Twig

Tags:

php

twig

I've added a macro to Twig and I'm trying to get that Macro to call itself. It appears that using _self appears to now be frowned on and doesn't work, returning the error:

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:

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

But I can't then call the macro recursively using _self or twigdebug.recursiveTree.

Is there a way to do this?

like image 621
user2353938 Avatar asked Jul 10 '26 05:07

user2353938


1 Answers

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>
like image 83
Massimiliano Arione Avatar answered Jul 16 '26 11:07

Massimiliano Arione