1

My question is related to this page... How can I add a dynamic "active" CSS class to the navigation on any given page?

Thank you in advance my code is the following:

<ul id="slide-in"> 
    {% nav menu in craft.entries.section('mainMenu') %}
        <li class="{{ menu.id == entry.id ? 'active' }}">
            <a href="{{ menu.menuLink[0].url }}">{{ menu.title }}</a>
        </li>
    {% endnav %}
</ul>

I am using Ben's code from this page but I am struggling to get this method working. I was wondering if someone could help me get to the bottom of this. I assume menu.id does not match entry.id and therefore the class is not added but how can I check the two id's are matching?

  • To debug just output them both during the loop: MenuID:{{ menu.id }} - EntryID:{{ entry.id }} – j00lz Jul 25 '15 at 1:52
  • Ah that is simple thank you for your help...They all have different menu.id but they all have an entry.id of 4 for some reason. How can I make it so that they match up making this active class work in a loop? @j00lz – Steve88 Jul 27 '15 at 12:53
  • @Steve88 They should all have the same entry.id. You only want the nav item to be 'active' when the current menu id in the loop (i.e. 4) matches the page's entry id which is 4. – Douglas McDonald Jul 27 '15 at 15:43
  • Right the entry.id relates to the entry passed from the current page you are viewing and menu.id from the nav loop.... I guess none of your mainMenu sections have an id of 4 ? – j00lz Jul 28 '15 at 6:25
  • Ah yes that makes snese, thanks for your help I'm quite new to this. @j00lz Thats correct all of my mainMenu sections are like 77, 78, 79 etc and the entry my entry id's are 2, 3 ,4, 5 etc ... so how can I match them up :) – Steve88 Jul 28 '15 at 8:12
8

My recommendation is to match the slugs as opposed to the ids as this is much easier to debug.

<ul id="slide-in"> 
    {% nav menu in craft.entries.section('mainMenu') %}
        DEBUG: Entry.slug={{ entry.slug }} 
        DEBUG: menu.slug={{ menu.slug }} 
        <li class="{{ menu.slug == entry.slug ? 'active' }}">
            <a href="{{ menu.menuLink[0].url }}">{{ menu.title }}</a>
        </li>
    {% endnav %}
</ul>

Then obviously remove the debug lines once everything is working as intended :)

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.