Inline variable in the Play framework 2.x Scala template
Solution 1
First you don't create a variable but a value meaning it's read only.
In your example you have created a value fullName
which is accessible inside the curly brackets.
@defining("Farmor") { fullName =>
<div>Hello @fullName</div>
}
Will print Hello Farmor
To define a value which is accessible globally in your template just embrace everything with your curly brackets.
E.g.
@defining("Value") { formId =>
@main("Title") {
@form(routes.Application.addPost, 'id -> formId) {
@inputText(name = "content", required = true)
<input type="submit" value="Create">
}
}
}
In the example you can use the value formId
anywere.
Solution 2
If you don't want to use the @defining
syntax you can define a reusable block
which will be evaluated every time you use it:
@fullName = @{
user.firstName + " " + user.lastName
}
<div>Hello @fullName</div>
With this same syntax you can also pass arguments to the block: https://github.com/playframework/Play20/blob/master/samples/scala/computer-database/app/views/list.scala.html
user1051870
Updated on June 24, 2022Comments
-
user1051870 almost 2 years
How to create an inline variable in the Play framework 2.x Scala template? Path from the Play's guide is not clear to me:
@defining(user.firstName + " " + user.lastName) { fullName => <div>Hello @fullName</div> }
-
monzonj over 10 yearsugly, convoluted! .... So much for all velocity/freemarker efforts to make views really clean and HTML-coder friendly. It seems that now the fashion is make html views a total mess sigh
-
Pedro over 10 yearsI agree! I dislike this syntax very very much.
-
kdkeck over 10 yearsExcept a reusable block will be re-executed every time it is used, while the value of the defining block will only be computed once.