Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
domdorn opened this issue Feb 2, 2018 · 3 comments
Open

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

domdorn opened this issue Feb 2, 2018 · 3 comments

Comments

@domdorn
Copy link
Member

domdorn commented Feb 2, 2018

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

@crater2150
Copy link

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 }

@marcospereira
Copy link
Member

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?

@halfninja
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants