Symfony2 Twig Unlimited Depth of Childhood

I have a self-join table in which each folder has a parent, and the depth of this is unlimited. One folder can have another folder as a parent, with no depth restrictions.

Today, my code looks like this, and I'm looking for a way to dig as deep as necessary without hard coding, every step down, maybe there is a way to define a twig function with a loop that calls itself every round in the loop?

<select id='parent' name='container'> <option value='none'>No parent</option> {% for folder in folders %} <option value='{{ folder.id }}'>{{ folder.name }}</option> {% for folder in folder.children %} <option value='{{ folder.id }}'>&nbsp;&nbsp;&nbsp;{{ folder.name }}</option> {% endfor %} {% endfor %} </select> 
+4
source share
2 answers

You need separate file rendering options, which recursively include:

 <select> <option value="none">No parent</option> {% include 'options.html.twig' with {'folders': folders, 'level': 0} %} </select> 

options.html.twig :

 {% for folder in folders %} <option value="{{ folder.id }}"> {% for i in range(0, level) %}&nbsp;{% endfor %} {{ folder.name }} </option> {% include 'options.html.twig' with {'folders': folder.children, 'level': level + 1} %} {% endfor %} 

I wrote this code right here, so don't expect it to be correct, but that should be enough to give you this idea.

+8
source

This must be done using recursion . I have never tested it with a twig, but you could develop a mechanism in which you include a template recursively.

So, your current template will include itself in a cycle until a certain condition is reached. So in your inner loop you need some kind of if clause.

Good luck;)

0
source

Source: https://habr.com/ru/post/1436146/


All Articles