Pawel Novikov
Pawel Novikov

Reputation: 495

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

Upvotes: 0

Views: 81

Answers (1)

Nikdyvice
Nikdyvice

Reputation: 101

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="#">{{ subCategory.id }}</a></li>
                            {% endif %}
                          {% endfor %}
                        </ul>
                    </li>
                {% endif %}
            {% endfor %}

Upvotes: 1

Related Questions