Declare variable in a Play2 scala template
How do you declare and initialize a variable to be used locally in a Play2 Scala template?
I have this:
@var title : String = "Home"
declared at the top of the template, but it gives me this error:
illegal start of simple expression """),_display_(Seq[Any](/*3.2*/var)),format.raw/*3.5*/(""" title : String = "Home"
Solution 1:
@defining("foo") { title=>
<div>@title</div>
...
}
basically, you have to wrap the block in which you are going to use it
Solution 2:
Actually, @c4k 's solution is working (and quite convenient) as long as you don't try to change the variable's value afterwards, isn't it?
You simply place this at the top of your template:
@yourVariable = {yourValue}
or, if it's a more complicated expression, you do this:
@yourVariable = @{yourExpression}
You can even work with things like lists like that:
@(listFromController: List[MyObject])
@filteredList = @{listFromController.filter(_.color == "red")}
@for(myObject <- filteredList){ ... }
For the given example, this would be
@title = {Home} //this should be at beginning of the template, right after passing in parameters
<h1> Using title @title </h1>
In the comments you said, that it gets typed to HTML type. However, that is only relevant if you try to overwrite @title
again, isn't it?
Solution 3:
scala template supports this, you can define variable in template
@import java.math.BigInteger; var i=1; var k=1
if you want to change its value in template
@{k=2}
example
@(title:String)(implicit session:play.api.mvc.Session)
@import java.math.BigInteger; var i=1; var k=1
^
<div id='LContent_div@i'>
^
<div id='inner_div_@k'></div>
^
</div>
Solution 4:
virtualeyes' solution is the proper one, but there is also other possibility, you can just declare a view's param as usually with default value, in such case you'll have it available for whole template + you'll keep possibility for changing it from the controller
:
@(title: String = "Home page")
<h1>Welcome on @title</h1>
controller:
def index = Action{
Ok(views.html.index("Other title"))
}
Note that Java controller doesn't recognise templates' default values, so you need to add them each time:
public static Result index(){
return ok(views.html.index.render("Some default value..."));
}