开发者

Playframework is active menu item / route

开发者 https://www.devze.com 2023-01-29 16:22 出处:网络
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 p开发者_如何学Pythoneopl

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 p开发者_如何学Pythoneople 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


This solution worked pretty well for me. It has the benefit to be very simple.

app/views/tags/navigationitem.js

%{
 boolean isMatch = request.path.startsWith(_href.toString());
}%
<li class="sliding-element">
#{if isMatch}
<h3>${_title}</h3>
#{/if}
#{else}
<a href="${_href}">${_title}</a>
#{/else}
</li>

app/views/tags/navigationmenu.js

#{js 'navigationmenu.js'/}
#{css 'navigationmenu.css'/}

<div id="navigation-block">
    <ul id="sliding-navigation">
        #{navigationitem title:'Home', href:@HomeController.index() /}
        #{navigationitem title:'Search Contact', href:@SearchByContactController.index() /}
        #{navigationitem title:'Edit Contact', href:@EditContactInfoController.index() /}
    </ul>
</div>


This code work for me guys

<li @if(request.path.startsWith("/artigo")){ class="active" }>
    <a href="@routes.ArtigoController.telaLista"> Artigos</a>
</li>
0

精彩评论

暂无评论...
验证码 换一张
取 消