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?
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 macros don't have access to the current template variables
You either have to import
self in template AND in the macro as well:
{% 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.
{% 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) }}