2

Here is the code I am trying to use to set an active state for category navigation:

    {% for category in categories %}
        <li {% if craft.request.segment(2) == "{{ category.slug }}" %}class="active"{% endif %}><a href="{{ category.url }}">{{ category.title }}</a></li>
    {% endfor %}

It seems that the conditional can't check against the category.slug output. Is this the case? What would be a better approach?

Any help is appreciated.

2

You don't need the quotes or braces in twig tags to reference variables.

{% for category in categories %}
    <li {% if craft.request.segment(2) == category.slug %}class="active"{% endif %}><a href="{{ category.url }}">{{ category.title }}</a></li>
{% endfor %}

You could also use ternary operators:

{% for category in categories %}
    <li {{ craft.request.segment(2) == category.slug ? 'class="active"' : "" }}><a href="{{ category.url }}">{{ category.title }}</a></li>
{% endfor %}
  • What if I wanted to set class based on the url having no segment 2? – jeff_nordstedt Jul 22 '14 at 16:00
  • I haven't tried it, but you could try using twig's default filter: craft.request.segment(2)|default("") – Bryan Redeagle Jul 22 '14 at 16:09
  • Actually, I guessed and answered my own follow up by replacing "category.slug" with "null" to set class when no category is selected. – jeff_nordstedt Jul 22 '14 at 16:10
1

Small update for Craft3 in the syntax :

{% set categories = craft.categories().all() %}
{% nav category in categories %}
    <li class="nav-menu-item {{ craft.app.request.getSegment(2) == category.slug ? 'nav-menu-item-current' : '' }}{% endif %}">
        <a href="{{ category.url }}">{{ category.title }}</a>
    </li>
{% endnav %}

PS. Is there any other way to achieve this ? Going through craft.app is apparently frowned upon : https://docs.craftcms.com/v3/templating/global-variables.html#craft-app

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.