Last Updated: March 30, 2017
·
703
· teito79

Dump an array inside a twig template with a nice bootstrap collapsable tree

This is the code of the template to be called:

<ul {% if level != 0 %} class="collapse" id="collapsable-{{ unique }}-{{ parent_index }}-{{ level }}"{% else %}{% endif %}>
{% for index, val in value %}
    {% if val is iterable %}
        <li>
            <a role="button" aria-expanded="false" aria-controls="collapsable-{{ unique }}-{{ parent_index ~ '-' ~ index }}-{{ level + 1 }}" data-toggle="collapse" href="#collapsable-{{ unique }}-{{ parent_index ~ '-' ~ index }}-{{ level + 1 }}">
                [{{ index }}] =>
            </a>
            {% include _self.templateName with { value: val, level: level + 1, parent_index: parent_index ~ '-' ~ index } %}
        </li>
    {% else %}
        <li>
            [{{ index }} =>
            {% if val.timestamp is defined %}
                {{ val.format('H:i:s d/m/Y') }}
            {% else %}
                {{ val }}
            {% endif %}
            ]
        </li>
    {% endif %}
{% endfor %}
</ul>

This is how the template is supposed to be included:

{% include 'AppBundle:Admin:_list_array.html.twig' with { value: result, parent_index: 0, level: 0, unique: random(100000) } %}