沃梦达 / 编程问答 / php问题 / 正文

Symfony2 Twig 无限子深度

Symfony2 Twig unlimited child depth(Symfony2 Twig 无限子深度)

本文介绍了Symfony2 Twig 无限子深度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自连接表,其中每个文件夹都有一个父级,并且其深度是无限的.一个文件夹可以有另一个文件夹作为父文件夹,没有深度限制.

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.

今天我的代码看起来像这样,我正在寻找一种方法来尽可能深入地挖掘,而无需对每一步进行硬编码,是否有一种方法可以定义一个带有循环的 twig 函数,它会调用自己在循环中的每一轮?

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>  

推荐答案

你需要一个单独的文件渲染选项,递归地包含自己:

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.

这篇关于Symfony2 Twig 无限子深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Symfony2 Twig 无限子深度

基础教程推荐