3

So I have a two-level Navigation in a structure. What I want is to give the parent of my entry (if a parent exists) the active tag.

right now I'm doing that:

{% for nav_item in navigation %}
  <li class="{% if craft.request.getSegment(1) == nav_item.nav_url %}active {% endif %}{% if nav_item.hasDescendants() %}more{% endif %}">

    <a href="{{nav_item.nav_url}}">{{nav_item.title}}</a>

  {% if nav_item.hasDescendants() %}
    <ul class="submenu">
      {% for child in nav_item.getChildren() %}
        <li>
            <a href="{{child.nav_url}}">{{child.title}}</a>
        </li>
      {% endfor %}
    </ul>
  {% endif %}
  </li>
{% endfor %}

sadly most children don't share the first segment

3 Answers 3

1

How a look at the isAncestorOf() method in the Docs. The given example code probably covers all you need:

{% set expanded = entry is defined and page.isAncestorOf(entry) %}
<li{% if expanded %} class="expanded"{% endif %}>

To only address the direct parent, use isParentOf() instead.

0

If it works for you to use the URL segments for comparisons, I posted an answer on how to do that here: "How can I add a dynamic “active” CSS class to the navigation on any given page?"

1
  • Sorry, only read that relevant line at the bottom of your post after posting this. Hopefully that other answer I just gave is more helpful :)
    – carlcs
    Oct 10, 2014 at 10:18
0

If you have an Entries field type in your navigation structure (like the more advanced example in this post on the craft cookbook) you should be able to use the relatedTo( ) parameter to do the comparison instead of using the segment in a URL.

For example if you had an Entries Field with the handle "relatedEntry" in your navigation structure you could change your code from this:

  <li class="{% if craft.request.getSegment(1) == nav_item.nav_url %}active {% endif %}{% if nav_item.hasDescendants() %}more{% endif %}">

to this:

{# Fetch the related navigation entry based on our current entry #}
{% set relatedToEntry = navigation.relatedTo(entry)%}

{# Check to see if the mainNavigation entry matches the current entry. Only compare it with the top level navigation items #}
{% set active = (relatedToEntry[0].slug == nav_item.slug and nav_item.hasDescendants) or (relatedToEntry[0].parent != "" and relatedToEntry[0].parent.slug == nav_item.slug) %}

{# display the class "active" if #}
<li class="{% if active %}active {% endif %}{% if nav_item.hasDescendants() %}more{% endif %}">
<a href="{{ nav_item.relatedEntry[0].url }}">{{ nav_item.title }}</a></li>

Note: For some reason I had to compare the slugs (as opposed to the names) in order to get a positive match.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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