@if(someOption){ value => .... } else { .... }
Today I tried to make use of a scala.Option in my twirl template but found it rather hard / unelegant to use it in a nice way.
what I had to do was
@if(myOption.isDefined) {
some code @myOption.get
} else {
some alternative code
}
What I wanted was something like a map with an else block, basically this kind of code
@if(myOption) { value =>
code when my value is @value
} else {
code when my value is not present
}
Is there something like this already? If not, how would I get started in providing a PR?
Is it a good idea to enhance the "if" with this or should I focus on implementing a new thing like @ifdefined(myOption) { value => ... } else { .. } ?
You can handle an option with pattern matching, like in plain scala:
@myOption match {
case Some(value) => { code using @value }
case None => { code when not present }
}
(note that for some reason, the braces around the single cases are not optional)
Or if you only care about the case, when a value is present:
@for(value <- myOption) { code using @value }
Or if you only care about the case, when a value is present:
@for(value <- myOption) { code using @value }
Given that, it could be more interesting to have a for-else construction? That would be useful in other cases like instead of:
@if(iterable.nonEmpty) {
@for(item <- iterable) {
show @item
}
} else {
Oops, no items to show.
}
We would have:
@for(item <- iterable) {
show @item
} else {
Oops, no items to show.
}
@domdorn what do you think?
What I wanted was something like a map with an else block
Other than requiring a dot to call .getOrElse I think the idiomatic Scala is pretty close to a standard if/else.
@myOption.map { value =>
code when my value is @value
}.getOrElse {
<strong>code when value is not present</strong>
}