PlayFramework2 how to get the current page URL in the form of templates

Originally posted and answered here:

https://groups.google.com/forum/#!topic/play-framework/s-ufMIbLz3c

But when I put:

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

But I got:

 '(' expected but ')' found. 
+7
source share
2 answers

Assuming you have a query object in scope, unfortunately, you just need to remove the space after the "if". Game templates are very interval sensitive. Try:

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

What you are trying to achieve is quite common, you are trying to show the current page in the menu, marking it as active.

Solution 1

You can really do what you did above. Add a few @if conditions with string comparisons in your template.

 @if(request.uri == "/"){ class="active" } 

Decision 2

But I like to go a little further in the type of secure architecture. Usually I create an object containing many constants:

 object MenuContants { val HOME = "HOME" val CONTACT = "CONTACT" } 

And then I give these constants in patterns. From the subtable to the main layout template:

 @main("The title of my page", MenuConstants.HOME) { // the rest of my template } 

And then, in your main template, make a comparison, but no longer on a string basis, but on constants that are type safe.

 @(title:String, contant:String) { @if(contant == MenuConstants.HOME) { class="active" } } 
+6
source share

All Articles