I would like to style the active menu item, to do this i need to compare the current url agains a route. I know that I can do this in javascript, but I was wondering how other people have solved this in play.
Any suggestions?
Pseudocode:
<a #{routeIsActive Application.index()} class="active"#{/if} href="@{Application.index()}">My Page</a>
<a #{if request.action=="Application.index"}class="active"#{/if} href="@{Application.index()}">My Page</a>
Easy. :D
Unfortunately, I couldn't find an easy way to do this. The simplest solution I could find was to write a fast tag (but this may be due to my lack of Groovy experience).
I got this working with this code.
In your View
<a class="#{activeRoute href:@Application.index(), activeClass:'active' /}" href="@{Application.index()}">My Page</a>
Then, create a new FastTag for activeRoute
public class MyFastTag extends FastTags {
public static void _activeRoute(Map<?, ?> args, Closure body, PrintWriter out, GroovyTemplate.ExecutableTemplate template, int fromLine) {
Router.ActionDefinition actionDef = (Router.ActionDefinition) args.get("href");
String activeStyle = (String) args.get("activeClass");
String inactiveStyle = (String) args.get("inactiveClass");
if (Http.Request.current().action.equals(actionDef.action) && activeStyle != null) {
out.print(activeStyle);
}
else if (!Http.Request.current().action.equals(actionDef.action) && inactiveStyle != null) {
out.print(inactiveStyle);
}
}
}
Make sure you add the relevant imports.
This allows you to specify an active and inactive class, which is a little more than you requested
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With