[2.0] how to get current page's URL in view templates?

2,983 views
Skip to first unread message

Chris B.

unread,
Apr 6, 2012, 12:45:32 AM4/6/12
to play-fr...@googlegroups.com
I want to customize the page's navigation menu if the page's URL is of a certain value: e.g. /, /blog, etc.

here is the pseudo code in view template, :

@if (current page's URL == "/") { "Home Menu Selected" }

how to implement this code? Is this the best way to approach this issue?


Korrawit Yindeeyoungyeon

unread,
Apr 6, 2012, 2:10:45 AM4/6/12
to play-fr...@googlegroups.com
You can pass request object to template view by using implicit request.


It is often useful to mark the request parameter as implicit so it can be implicitely used by other APIs that need it:

Action { implicit request =>
  Ok("Got request [" + request + "]")
}


Then in your controller,

def index = Action { implicit request =>
    Ok(views.html.index())
}

In your view,

@(message: String)(implicit request: play.api.mvc.Request[Any])
@main("Index") {
<div>
                @if (request.uri == "/") { "Home Menu Selected" }
</div>
}

Chris B.

unread,
Apr 6, 2012, 3:36:37 PM4/6/12
to play-fr...@googlegroups.com
it works. thank you.
Message has been deleted
Message has been deleted

Sergii Starodubtsev

unread,
Sep 16, 2013, 9:04:21 PM9/16/13
to play-fr...@googlegroups.com
If I put:

<div>
 @if (request.uri == "/") { "Home Menu Selected" }
</div>

I got

'(' expected but ')' found.

sunnykaka

unread,
Aug 17, 2015, 11:04:47 PM8/17/15
to play-framework

If you're using Play for Java, you can do something this:

<li @if(requestHeader.uri == routes.Help.index.url){class="active"}>

Just ignore the error in your ide, it compiles and run well.

The requestHeader method was import automatically by class play.TemplateImports:

javaImports.add("play.core.j.PlayMagicForJava._");

Reply all
Reply to author
Forward
0 new messages