1

I've coded up conditional for categories. I'm still new to Twig and curious if there is a simpler way of coding the following.

{% for feedItems in craft.entries.section('news').limit(null).offset(1).find() %}

{% set parent = craft.categories.slug('parent-category').first() %}
{% set child = feedItems.generalCats.descendantOf(parent).level(2) %}

{% set parentLvl = feedItems.generalCats.level(1).find() %}
{% set childLvl = feedItems.generalCats.level(2) %}

{% if childLvl | length %}
    {% for category in child.limit(1) %}
        {% if child.count() > 1 %}
            <a href="{{ parent.url }}">{{ parent.title }}</a>
        {% else %}
            <a href="{{ category.url }}">{{ parent.title }}</a>
        {% endif %}
    {% endfor %}
    {% else %}
    {% for category in parentLvl %}
        <a href="{{ category.url }}">{{ category.url }}</a>
    {% endfor %}
{% endif %}

{% endfor %}

This is currently outputting the child category if there isn’t more than one child cat selected. If there is more than 1 child cat selected it outputs the parent category. If any of the former is false (no children or parent) it outputs one of the other 1st lvl cats (doesn’t have children)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.