-
-
Save tentacode/3892186 to your computer and use it in GitHub Desktop.
{% macro recursiveCategory(category) %} | |
<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 %} | |
{% if categories %} | |
<div id="categories"> | |
<ul> | |
{% for category in categories %} | |
{{ _self.recursiveCategory(category) }} | |
{% endfor %} | |
</ul> | |
</div> | |
{% endif %} |
"When you define a macro in the template where you are going to use it, you might be tempted to call the macro directly via _self.input() instead of importing it; even if seems to work, this is just a side-effect of the current implementation and it won't work anymore in Twig 2.x." http://twig.sensiolabs.org/doc/tags/macro.html
hi.. it was very very useful.. but this macro generates a lot of queries to get all items.. is there a way to do this recursive function without to do much queries? or is there a kind of optimization that turns these queries in something "soft"?
Thanks so much for posting this. It took a while to finally find it, but I've been struggling with recursive twig macros for an hour now.
@cccc: I don't think, that this will affect the actual recursion call _self.recursiveCategory(child)
inside the macro but the initial call in the template self. This can be fixed by using:
{# Twig 2.x compatible version #}
{# ... macro ... #}
{% import _self as macros %}
{% if categories %}
<div id="categories">
<ul>
{% for category in categories %}
{{ macros.recursiveCategory(category) }}
{% endfor %}
</ul>
</div>
{% endif %}
very good! thank you
Thanks!
This works perfectly! Outstanding.
Well done ! Thank you :)
It looks like this is deprecated and will not work anymore in twig 2 😢
See https://gist.github.com/garak/0c7cc873c70c09863641401981f81442 for a working solution
thanks!
Another solution for this situation is to use the "tree" twig tag: https://github.com/jordanlev/twig-tree-tag -- it's less hacky, works in Twig 1 and 2, and IMO keeps the markup more straightforward (less ceremony around the mechanics of the loop and/or the macro). Only potential problem is that it requires PHP 5.4 or higher (but if you're using Twig v2 then that's no problem because you're already on PHP 5.5 or higher for that).
@ureimers your example gives exception:
Impossible to invoke a method ("recursiveCategory") on a string variable ("...html.twig").
Hi!
How to be with categories duplicates.
I mean if category has been rendered as a child, but it also will be rendered as a root category? So on page will be the two same categories rendered as a child category and as a root category.
Kind regards
thanks!