score:8
Assuming you have the request object in scope, sadly enough you just need to remove the space after "if". Play templates are pretty sensitive about spacing. Try:
<div>
@if(request.uri == "/") { "Home Menu Selected" }
</div>
score:0
To answer the question
The implicit Request, available to the templates, has all the details. Adapted to the example in the question I would use the following template function, which was tested in Play Framework 2.6. It does not require to maintain an enum but you still stay safe when updating your routes
file and get compile errors when you rename the actions.
@*
Usage:
<div>
@outputIf(routes.HomeController.index, "Home Menu Selected")
</div>
*@
@outputIf(call:play.api.mvc.Call, text:String) = @{
if (request.path.equals(call.path)) text else ""
}
Documentation
There is some documentation about reusable blocks: https://www.playframework.com/documentation/2.6.x/ScalaTemplates#Declaring-reusable-blocks
play.api.mvc.Call API: https://www.playframework.com/documentation/2.6.x/api/scala/index.html#play.api.mvc.Call
play.api.mvc.Request API: https://www.playframework.com/documentation/2.6.x/api/scala/index.html#play.api.mvc.Request
My intention (rendering Navigation)
I recently stumbled across a related Problem and after i found nothing specific to my problem on the web aside from this post, i'd like to share my final solution with you.
I'd wanted to render navigation list items with an 'active' class if the current url of the page is equal to the list items' url but neither did I like to just compare the url-string for equality as it may change and would give no compile errors - nor did I accept to create and update an enum every time I add a new navigation item (as I have an increasing amount of them including children). However I still wanted to stay safe when changing the routes
urls at some time.
In Play Framework 2.6 I solved the problem using this reusable function within the main.scala.html
template:
@*
Renders a list item <li> with active-class containing a link element
Usage:
@navItem(routes.HomeController.index, "Home")
@navItem(routes.HomeController.index, "Home", "nav-home")
@navItem(routes.HomeController.index, "Home", activeClass="selected")
@navItem(routes.HomeController.index, "<span>Home</span>", "nav-home nav-element", "selected active")
*@
@navItem(call:play.api.mvc.Call, linkContent:String, cls:String="", activeClass:String="active") = @{
val hrefAttr = "href='"+call+"'"
val classNames = if (request.path.equals(call.path)) activeClass + " " + cls else cls
val classAttr = if(classNames.length>0) " class='"+classNames+"'" else ""
val linkHtml = Html(linkContent)
Html("<li"+classAttr+"><a "+hrefAttr+">"+linkHtml+"</a></li>")
}
the comment example renders to the following in case the Homepage is requested:
<li class="active"><a href="/">Home</a></li>
<li class="active nav-home"><a href="/">Home</a></li>
<li class="selected"><a href="/">Home</a></li>
<li class="selected active nav-home nav-element"><a href="/"><span>Home</span></a></li>
score:7
What you are trying to achieve is quite common, you are trying to show the current page in a menu by marking it as active.
Solution 1
You can indeed do what you did above. Add several @if conditions with string comparisons in your template.
@if(request.uri == "/"){ class="active" }
Solution 2
But I like to go a little further in the type safe architecture. I generally create an object containing a lot of constants :
object MenuContants {
val HOME = "HOME"
val CONTACT = "CONTACT"
}
And then I give those constants around in the templates. From sub-template to the master layout template :
@main("The title of my page", MenuConstants.HOME) {
// the rest of my template
}
And then in your main template, do the comparison but no longer based on strings but on constants, which is type-safe.
@(title:String, contant:String) {
@if(contant == MenuConstants.HOME) { class="active" }
}
Source: stackoverflow.com
Related Query
- PlayFramework2 how to get current page's URL in view templates
- How do we get the current page URL in Lift snippets?
- How to get the current date without time in scala
- How can I get the current SparkSession in any place of the codes?
- How to get the line separator of current os easily in Scala?
- Play Framework 2.1: Scala: how to get the whole base url (including protocol)?
- How to get the current (working) directory in Scala?
- How to get IntelliJ to recognize Play Framework *.scala.xml Templates
- How can I get a Random URL on http request for Gatling?
- How to get current timestamp in Scala as a string without spaces?
- How to correctly get current loop count from a Iterator in scala
- How do I get the scalaz IDEA live templates working for the symbolic methods?
- How do I get the absolute remote actor url from inside the actor?
- How do I use Scala dispatch to get the URL returned in a 301 redirect?
- Gatling in scala how to get url from redirect
- How to get current date, month, year in scala
- How to get list of all Route URL strings in play framework?
- How to get current position of iterator in ByteString?
- How to get number of cores used in current job?
- How do I get the current script or class name in Scala?
- How to get current project name in sbt build.scala
- how to get current application instance in companion object
- How to get the full URL from an Http4s Request
- How to get current iteration step in Flink's iterators?
- How to get Play current when using it in a trait?
- Play Framework: How to get the current port number
- How to retrieve current url in the main.scala.html template page
- how to get the Hadoop-spark job's tracking URL or catch the spark-submit output by scala code
- How do you get the POST request object or URL string in Play Framework's WS API?
- Scala: How do I get the current time in RFC 822 / 1123 format
More Query from same tag
- Scala: Making higher kinded type with some generic type
- Converting Java to Scala
- What functional technique enables not having to pass configuration through functions
- Scala passing varargs to another function that takes varargs
- Parse JSON in Scala using JSON4S
- How to access a class's type parameter in Scala
- How do I algorithmically instantiate and manipulate a multidimensional array in Scala
- Scala Slick Bulk Insert with Array
- When do before() and after() get invoked within a ScalaTest class with BeforeAndAfter trait
- how to use go to different branch if a string contains different words in scala using match/case?
- sbt stuck while downloading
- spark sql window function lag
- Stackoverflow Exception using Scala actors and receiveWithin
- Zeppelin %sql cannot access temporary table
- GroupBy + custom aggregation on Dataset with Case class / Trait in the Key
- Why does a function literal used as a default argument require a parameter type?
- How do I short this scala code?
- Get parent Enumeration of Value typetag
- Invoke a method using a tuple as the parameter list
- What is the best way to create a new Play! 2.1 module?
- Scala-Java interop, issue with overloading of methods (Array and varargs)
- Scala: sort list by sum of duration
- Spark Streaming with Kafka in Scala
- How do I match types that don't have a specific typeclass instance?
- Remember me functionality - simplest way
- Parser Alternative Operator | Fails
- recursive call Future in scala
- Declare natural transform for batching with kind-projector
- Scala two map merge
- Finding values within broadcast variable