Pawel Novikov Pawel Novikov - 4 months ago 10
HTML Question

IF statement doesn't work in another IF statement in Twig

I have such construction in my twig template

{% for category in categories %}
{% if category.parentId == 0 %}
{% set parent = category.id %}
<li class="menu-item dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
{{ category.name }}
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
{% if category.parentId == parent %}
<li><a href="#">{{ category.id }}</a></li>
{% endif %}
</ul>
</li>
{% endif %}
{% endfor %}


My problem is in that, that second condition IF (if category.parentId == parent) doesn't work, so, I can't get list of subcategories.

Does anybody know, what a problem there and how can I solve it?

Thanks

Answer

If statement in twig is working properly, but you have mistake there. You compare category.id with category.parentId in the same object. You have to have another foreach loop for sub categories. Like this:

{% for category in categories %}
                {% if category.parentId == 0 %}
                    {% set parent = category.id %}
                    <li class="menu-item dropdown">
                        <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                            {{ category.name }}
                            <span class="caret"></span>
                        </a>
                        <ul class="dropdown-menu">
                          {% for subCategory in categories %}
                            {% if subCategory.parentId == parent %}
                                <li><a href="#">{{ category.id }}</a></li>
                            {% endif %}
                          {% endfor %}
                        </ul>
                    </li>
                {% endif %}
            {% endfor %}