Programing

Twig에서 나무를 렌더링하는 방법

lottogame 2020. 9. 7. 22:26
반응형

Twig에서 나무를 렌더링하는 방법


깊이가 결정되지 않은 나무를 렌더링하고 싶습니다 (자녀의 자식 등). 배열을 재귀 적으로 반복해야합니다. Twig에서 어떻게 할 수 있습니까?


감사합니다 domi27, 나는 당신의 아이디어를 가지고 놀았고 이것을 생각해 냈습니다. 내 트리로 중첩 배열을 만들었습니다. [ 'link'] [ 'sublinks']는 null이거나 더 많은 다른 배열입니다.

템플릿

재귀 할 하위 템플릿 파일 :

<!--includes/menu-links.html-->
{% for link in links %}
    <li>
        <a href="{{ link.href }}">{{ link.name }}</a>
        {% if link.sublinks %}
            <ul>
                {% include "includes/menu-links.html" with {'links': link.sublinks} %}
            </ul>
        {% endif %}
    </li>
{% endfor %}

그런 다음 기본 템플릿에서 이것을 호출하십시오 (일부 중복 'with'것).

<ul class="main-menu">
    {% include "includes/menu-links.html" with {'links':links} only %}
</ul>

매크로

매크로를 사용하여 유사한 효과를 얻을 수 있습니다.

<!--macros/menu-macros.html-->
{% macro menu_links(links) %}
    {% for link in links %}
        <li>
            <a href="{{ link.href }}">{{ link.name }}</a>
            {% if link.sublinks %}
                <ul>
                    {{ _self.menu_links(link.sublinks) }}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
{% endmacro %}

기본 템플릿에서 다음을 수행하십시오.

{% import "macros/menu-macros.html" as macros %}
<ul class="main-menu">
    {{ macros.menu_links(links) }}
</ul>

도움이되기를 바랍니다 :)


동일한 템플릿에서 매크로 를 사용하려면 Twig 2.x와 호환되도록 다음과 같은 것을 사용해야합니다 .

{% macro menu_links(links) %}
    {% import _self as macros %}
    {% for link in links %}
        <li>
            <a href="{{ link.href }}">{{ link.name }}</a>
            {% if link.sublinks %}
                <ul>
                    {{ macros.menu_links(link.sublinks) }}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
{% endmacro %}

{% import _self as macros %}

<ul class="main-menu">
    {{ macros.menu_links(links) }}
</ul>

This extends random-coder's answer and incorporates dr.scre's hint to the twig documentation about macros to now use _self but import locally.


Edit (2019-07-01):

As of Twig 2.11 you can omit the {% import _self as macros %}, as inlined macros are imported automatically under the _self namespace (see Twig anouncement: Automatic macro import):

{# {% import _self as macros %} - Can be removed #}

<ul class="main-menu">
    {{ _self.menu_links(links) }} {# use _self for inlined macros #}
</ul>

If you're running PHP 5.4 or higher, there is a wonderful new solution (as of May 2016) to this problem by Alain Tiemblo: https://github.com/ninsuo/jordan-tree.

It's a "tree" tag that serves this exact purpose. Markup would look like this:

{% tree link in links %}
    {% if treeloop.first %}<ul>{% endif %}

    <li>
        <a href="{{ link.href }}">{{ link.name }}</a>
        {% subtree link.sublinks %}
    </li>

    {% if treeloop.last %}</ul>{% endif %}
{% endtree %}

First i thought, this may be solved straightforward - but it isn't that easy.

You need to create a logic, maybe with a php class method, when to include a twig subtemplate and when not.

<!-- tpl.html.twig -->
<ul>
{% for key, item in menu %}
    {# pseudo twig code #}
    {% if item|hassubitem %}
        {% include "subitem.html.tpl" %}
    {% else %}
        <li>{{ item }}</li>
    {% endif %}
{% endfor %}
</ul>

So you could use the special twig loop variable , which is available inside a twig for loop. But i'm not sure about the scope of this loop variable.

Sorry for provide only an approach not a solution, but perhaps i hope my thoughts may help you (a little bit).

This and other informations are available on Twigs "for" Docu !


Took flu's answer and modified it a little:

{# macro #}

{% macro tree(items) %}
    {% import _self as m %}
        {% if items %}
        <ul>
            {% for i in items %}
                <li>
                    <a href="{{ i.url }}">{{ i.title }}</a>
                    {{ m.tree(i.items) }}
                </li>
            {% endfor %}
        </ul>
    {% endif %}
{% endmacro %}

{# usage #}

{% import 'macros.twig' as m %}

{{ m.tree(items) }}

The answers here lead my to my Solution.

I have a Category Entity with self referencing ManyToOne association (parent to children).

/**
 * @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
 */
private $parent;

/**
 * @ORM\OneToMany(targetEntity="Category", mappedBy="parent")
 */
private $children;

In my twig template i am rendering the tree view like this:

<ul>
{% for category in categories %}
    {% if category.parent == null %}
        <li>
            <a href="{{ category.id }}">{{ category.name }}</a>
            {% if category.children|length > 0 %}
            <ul>
            {% for category in category.children %}
                <li>
                    <a href="{{ category.id }}">{{ category.name }}</a>
                </li>
            {% endfor %}
            </ul>
            {% endif %}
        </li>
    {% endif %}
{% endfor %}
</ul>

참고URL : https://stackoverflow.com/questions/8326482/how-to-render-a-tree-in-twig

반응형