I'm having a hard time getting the "active" class to stay across different pages. I have the navbar loading on each page via a layout, could this be the issue?
2 Answers
I just have this inside my layout gsp for creating the navbar, and it works perfectly. I only have items in the navbar at the level of the controller, not for individual actions.
<li ${controllerName.equals('schedule') ? 'class="active"' : ''}>Schedule</li>
For the default controller generated by Grails, you can use
<li ${controllerName == null ? 'class="active"' : ''}>Home</li>
-
Thanks for making it pretty! I'll have to get a hang of the (mini)markdown.– tanwedarOct 4, 2012 at 16:15
-
This works fine. But I have another problem. When you change this to active and the main.gsp is loaded again, There are two active li elements. Would you know how to get around this? Nov 7, 2015 at 5:11
Yes, that is the issue.
Whenever you reload the page, whatever <li>
element has class=active
will be set to active again.
If you have /grails-app/views/layouts/main.gsp
with the following:
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li class="active"><a href="/home">Home</a></li>
<li><a href="/fred">Fred</a></li>
<li><a href="/barney">Barney</a></li>
</ul>
</div>
</div>
And your GSPs for Fred and Barney use the main.gsp layout, when you click on them, you will load the code above and the link for "Home" will still be active.
Solutions are to write a Taglib for the Navbar control, or create separate layout pages.
-
Writing multiple layouts seems like a waste. Would the taglib simply render active or not based on the current page?– tanwedarSep 18, 2012 at 20:34
-
I agree, the multiple layouts would be overkill in the event that the only layout content you are changing is the active item. As you said, your taglib would just render
class="active"
or not depending on the current page. Here is how someone did it in PHP: stackoverflow.com/questions/11813498/… Sep 18, 2012 at 20:42 -
1I made, probably an ugly in experienced programmers' eyes, taglib. I pass it ${controllerName}${actionName} and the controller/action that the button represents and do a simple == check.– tanwedarSep 18, 2012 at 21:03
<li>
.<trail:navbarActiveLink current="${controllerName}${actionName}" test="usermanageUsers"/>
I can't figure out how to do the block code really....everything online keeps saying to click the brackets button, which I dont have... I use a simple check.if(attrs.current == attrs.test)
and follow that byout << 'class="active"'