twirl icon indicating copy to clipboard operation
twirl copied to clipboard

@if(someOption){ value => .... } else { .... }

Open domdorn opened this issue 7 years ago • 3 comments

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 { .. } ?

domdorn avatar Feb 02 '18 14:02 domdorn

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 }

crater2150 avatar Feb 28 '18 09:02 crater2150

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?

marcospereira avatar Feb 28 '18 20:02 marcospereira

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>
}

halfninja avatar Oct 17 '19 08:10 halfninja