1

I have a simple nav set up using Globals in a table, but I'm struggling to get it to add an active class to only the active page.

The below code adds the nav links, but I need to know what to add to it to get the active class on only the current page.

Need a little help please?

{% if mainNav.navitems|length %}
    {% for row in mainNav.navitems %}
        <li><a href="{{ row.url }}">{{ row.name }}</a></li>
    {% endfor %}
{% endif %}

Main Nav

2

Depends on your URL structure ultimately and whether you have sub pages, but I think the easiest way to do it would be something like:

{% if mainNav.navitems|length %}
 {% for row in mainNav.navitems %}
  <li>
    <a href="{{ url(row.url) }}"
     {%- if craft.request.segment(1) == row.url %}class="active"{%- endif %}>
     {{ row.name }}
    </a>
  </li>
 {% endfor %}
{% endif %}

You don't have to use the segment(1) method if it doesn't suit, take a look at the request docs to find something that suits your URLs

  • Thanks alec, I managed to solve it just before you answered. But in your one the active class would be added to the <a> tag, so wouldn't work as needs to go on the <li> – mention79 Jun 8 '17 at 9:47
1

I have solved it {% if row.url == craft.request.firstSegment %}class="active" {% endif %}

Here's the full code.

{% if mainNav.navitems|length %}
{% for row in mainNav.navitems %}
  <li {% if row.url == craft.request.firstSegment %}class="active" {% endif %}><a href="{{ row.url }}">{{ row.name }}</a></li>
{% endfor %}
{% endif %}

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.