Reputation: 755
I wonder if play 2.0.3 and higher supports else if
in views? I only read that one have to code that way: if {...}else{if{...}else{...}}
cannot believe that.
Upvotes: 40
Views: 25401
Reputation: 5123
Now if else if
is supported in latest playframework. Discussion is here https://github.com/playframework/twirl/issues/33
You can use like this:
@if(something) {
...
} else if (somethingElse) {
...
} else {
...
}
Upvotes: 3
Reputation: 561
The @Todd Flanders answer is right. In a wrapper @{}, you can write your normal Scala code. Example
@{
if (profile.sex == 0) {
<p class="col-md-6">Other</p>
} else if (profile.sex == 1) {
<p class="col-md-6">Male</p>
} else {
<p class="col-md-6">Female</p>
}
}
Upvotes: 29
Reputation: 3503
You can use switch statement
in Scala
to achieve it.
Example:
if(x>2){
<block 1>
} else if(x>0) {
<block 2>
} else {
<block 3>
}
Translated:
x match {
case x if(x>2) => {<block 1>}
case x if(x>0) => {<block 2>}
case _ => {<block 3>}
}
Hope can help you in some cases and hope play framework will support else if
soon.
Upvotes: 1
Reputation: 1175
I used an @ before the second if :
@if (true) {
...
} else { @if (true) {
...
} else {
...
}}
Upvotes: 35
Reputation: 461
No, "else if" is not supported in scala templates: Does play framework 2.0 support nested if statement in template?
You can use pattern matching or you can put if inside else.
Upvotes: 1
Reputation: 55798
No, it doesn't. It allows you only for if(condition) {then...} else {otherwise...}
For more possibilities you need to use Pattern Matching (similar to PHP's switch()
)
In this case _
is a default option.
Sample from previous version of Play Autheticate (now the same is done with reflections in the controller)
@(url: String, token: String, name: String)
@defining(lang().code) { langcode =>
@langcode match {
case "de" => {@_password_reset_de(url,token,name)}
case "pl" => {@_password_reset_pl(url,token,name)}
case _ => {@_password_reset_en(url,token,name)}
}
}
So maybe best option for you will be resolving the condition in the controller and passing it as a param to the view?
Upvotes: 10
Reputation: 383
I was also able to get
@{if (true) "foo" else if (true) "bar" else "baz"}
to work. Keep in mind that most programming languages do not support "else if" as a lexical token. They are separate commands. The block of code executed by the "else" command happens to be an "if" statement.
Note also that you can mix XHTML with the clause:
@{if (true) <b>foo</b> else if (false) "bar" else "baz"}
I agree with biesior that it's usually a good idea to push state logic into the controller, then you can have different views for different states, with shared components having their own sub-views.
Upvotes: 16