0

I'm trying to pull out selected categories in a front-end user profile. The cats have 2 levels and need to be pulled out into a nested list with only the selected options. I've tried different ways of doing this but nothing seems to work by using one for loop. So have nested the second level cats in a second for loop. This will work but the loop.first and loop.last variables are using the parent for loop and not the nested one? Or is there a better/easier way of doing this?

{% for challenge in user.challenges.level(1).options %}
    <li>
        {{ challenge.title }}
        {% for child in user.challenges.level(2).options %}
            {% if child and child.getParent().id == challenge.id %}
                {% if loop.first %}<ul>{% endif %}
                    <li>{{ child.title }}</li>
                {% if loop.last %}</ul>{% endif %}
            {% endif %}
        {% endfor %}
    </li>
{% endfor %}

1 Answer 1

1

You should be able to access the outer loop.index etc using the loop.parent context. The Twig docs here should give you what you need.

EDIT: You might be getting strange results because the inner loop contains an if so depending on your conditions you might loop over the first item thus making your inner loop.first not work as expected. You can combine for with an if which might get you a bit closer, like this:

{% for thing in things if thing.isAvailable == true %}
{{-- Your inner stuff --}}
{% endfor %}

More info here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.