Skip to content

Instantly share code, notes, and snippets.

@tentacode
Created October 15, 2012 12:23
Show Gist options
  • Select an option

  • Save tentacode/3892186 to your computer and use it in GitHub Desktop.

Select an option

Save tentacode/3892186 to your computer and use it in GitHub Desktop.
Twig recursive macro
{% 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 %}
@joshbloomfield

Copy link
Copy Markdown

Thanks!

@mriso79

mriso79 commented Mar 7, 2016

Copy link
Copy Markdown

This works perfectly! Outstanding.

@richard-integral

Copy link
Copy Markdown

Well done ! Thank you :)

@garak

garak commented Jan 2, 2017

Copy link
Copy Markdown

It looks like this is deprecated and will not work anymore in twig 2 😢

@garak

garak commented Jan 2, 2017

Copy link
Copy Markdown

@dimd13

dimd13 commented Apr 4, 2017

Copy link
Copy Markdown

thanks!

@jordanlev

jordanlev commented Apr 16, 2017

Copy link
Copy Markdown

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).

@AlexanderMatveev

Copy link
Copy Markdown

@ureimers your example gives exception:

Impossible to invoke a method ("recursiveCategory") on a string variable ("...html.twig").

@Smanst3r

Copy link
Copy Markdown

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment