Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare variable in a Play2 scala template

@defining("foo") { title=>
  <div>@title</div>
  ...
}

basically, you have to wrap the block in which you are going to use it


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?


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>

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..."));
}