6

I have a category group with parents each with 1 level of children.

On my category entry page I want to list JUST the children of the current category being viewed.

I'm sure it's simple but I can't figure what to put in my category template?

Many thanks in advance.

Martin

5

You should actually already have a variable named "category" pre-assigned by Craft, if you've set up your categories to have URLs in the category settings.

So this simplified code is probably all you need.

{% set subCategories = craft.categories.descendantOf(category) %}

{% if subCategories|length %}
    <ul>
        {% for category in subCategories %}
            <li><a href="{{ category.url }}">{{ category.title }}</a></li>
        {% endfor %}
    </ul>
{% else %}
    {% exit 404 %}    
{% endif %}

To have different template code for your sub-category pages you're linking to, I would put the code above in a partial _partials/mainCategory and include it with the include function.

{% if category.level == 1 %}
    {% include '_partials/mainCategory' %}
{% else %}
    {% include '_partials/subCategory' %}
{% endif %}
1

Of course after posting my question I immediately find an answer!!!

Would be good if someone can confirm this is the best way?

      {% set categories = craft.categories.group('areaOfPractice') %}
        {% for category in categories %}
          {% set thisIsActiveCategory = (category.slug == craft.request.segment(2)) %}
            {% if thisIsActiveCategory %}
              {% set subCategories = craft.categories.descendantOf(category) %}
              <ul>
                {% for subCat in subCategories %}
                <li><a href="{{ subCat.url }}">{{ subCat.title }}</a></li>
                {% endfor %}
              </ul>
            {% endif %}
        {% endfor %}

Your Answer

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

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