Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Twig unlimited child depth

Tags:

php

twig

symfony

I have a self-joining table where each folder has a parent, and the depth of this is unlimited. One folder can have another folder as a parent, no restriction on the depth.

Today my code looks like this, and I am looking for a way of digging down as deep as it needs without hard-coding each step down, is there perhaps a way to define a twig function with a loop, that calls itself on each 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>  
like image 564
Matt Welander Avatar asked Jan 15 '23 11:01

Matt Welander


1 Answers

You need a separate file rendering options that recursively includes itself:

<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 it should be enough to give you the idea.

like image 60
Elnur Abdurrakhimov Avatar answered Jan 24 '23 22:01

Elnur Abdurrakhimov