for-looptwigcountertwig-filter

Use twig "loop.length" inside a loop and then use it outside that loop


I,m try to implement a menu subitems counter on every menu item using Twig "loop.length". Acording to twig docs here i can access the variable if i declare it before the loop:

    <div id="menu">
        <div class="list-group">
            {% if menuItems %}
            {% set items = menuItems %}
            {% for item in items %}
            <a href="#">{{ item.title }}</span>{{ subitem_counter }}</span></a>
            {% if item.items %}
            <div class="list-subgroup">
                {% set subitem_counter = "" %}
                {% for subitem in item.items %}
                {% set subitem_counter = loop.length %}
                <a href="#">{{ subitem.title }}</a>
                {% endfor %}
            </div>
            {% endfor %}
            {% endif %}
        </div>
    </div>

The problem is that somehow on the first menu item i dont get any data on "subitem_counter", on second menu item i get count data from first menu subitems, on third menu item i get count data from second menu subitems e.t.c...


Solution

  • use length twig filter:

    <div id="menu">
        <div class="list-group">
            {% if menuItems %}
                {% set items = menuItems %}
                {% for item in items %}
                    <a href="#">{{ item.title }}</span>{{ item.items|length }}</span></a>
                    {% if item.items %}
                        <div class="list-subgroup">
                        {% for subitem in item.items %}
                            <a href="#">{{ subitem.title }}</a>
                        {% endfor %}
                        </div>
                {% endfor %}
            {% endif %}
        </div>
    </div>
    

    you can not use a variable's value, before you assign a value to it.