user3266289
user3266289

Reputation: 89

twig looping empty result

i'm building a navigation menu when I loop the results from database it's working properly with this code

 foreach ($menu as $item) {
    echo $item->name_english . ' ';
    if ($item->childs->count()) {
        foreach ($item->childs as $row) {
            echo $row->name_english . ' | ';
        }
    }
 }

and this id the output

first second child1| child2 | third fourth

when I use the same code in twig I get no results from childs loop

{% if menu %}
<ul>
    {% for item in menu %}
        <li>{{ item.name_english }}</li>
        {% if item.childs.count() %}
            <ul>
                {% for stuff in item.childs %}
                    <li>{{ stuff.name_english }}</li>
                {% endfor %}
            </ul>
        {% endif %}
    {% endfor %}    
</ul>

{% endif %}

and this is the output

Upvotes: 2

Views: 2814

Answers (1)

oshell
oshell

Reputation: 9103

To check the count of an array in twig you use length filter. Moreover you should be more specific when using twig. use menu is not null instead of menu.

{% if menu is not null and menu|length > 0 %}
<ul>
    {% for item in menu %}
        <li>{{ item.name_english }}</li>
        {% if item.childs|length > 0 %}
            <ul>
                {% for stuff in item.childs %}
                    <li>{{ stuff.name_english }}</li>
                {% endfor %}
            </ul>
        {% endif %}
    {% endfor %}    
</ul>

{% endif %}

Upvotes: 2

Related Questions