3

I have a category page displaying only the entries associated with the respective category. I have added a dynamic sub nav for categories using the following:

<ul>
    {% nav category in craft.categories.group('biographySection') %}
        <li>
            <a href="{{ category.url }}">{{ category.title }}</a>
        </li>
    {% endnav %}
</ul>

I need to add an active class on the active link. Can’t figure out the best way to do this. Any help is appreciated.

Below is the code used to display the content from a selected category:

{% set bio = craft.entries.section('biographies').relatedTo(category).find() %}
{% for entry in bio %}
    {{ entry.title }}
{% endfor %}
  • You're using this nav on an entries page, not a category page, right? – carlcs Jan 25 '15 at 23:26
  • I’m sorry. Using this on a category page. – Clint Tabone Jan 26 '15 at 9:13
2

If you're using the nav on a category page, this should do what you want:

You need to name your two category variables differently, so that you can compare them in the nav loop. So let's get the currently displayed category using getLastSegment() and save the CategoryModel to a var currentCategory.

{% set categorySlug = craft.request.getLastSegment() %}
{% set currentCategory = craft.categories.group('compositions').slug(categorySlug).first() %}

The CategoryModel that is returned from the loop we simply name category. Within the loop compare the IDs of the two CategoryModels.

{% nav category in craft.categories.group('biographySection') %}
    <li>
        {% set activeClass = category.id == currentCategory.id ? 'active' %}
        <a href="{{ category.url }}" class="{{ activeClass }}">{{ category.title }}</a>
    </li>
{% endnav %}
2

If you're using the nav on an entries page, this is how you'd do that:

You can check if an ElementCriteriaModel with the following criteria returns anything using the length filter. The ID of the entries must match your current entry's ID and they must be related to the currently looped category.

<li>
    {% set activeClass = craft.entries.id(entry.id).relatedTo(category)|length ? 'active' %}
    <a href="{{ category.url }}" class="{{ activeClass }}">{{ category.title }}</a>
</li>

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.