Dealing with Options in Scala Play Template
Asked Answered
T

5

6

I am trying reference things of type option in my Scala Play template. I've been trying to use this resource: http://www.playframework.com/modules/scala-0.9/templates

This is how I am trying to reference a field in the case class:

@{optionalobject ?. field}

and it is not working, this is the error I am getting:

';' expected but '.' found.

I am unsure why I am getting this error.

Thrasonical answered 12/12, 2013 at 20:32 Comment(0)
O
6
@optionalobject.map(o => o.field).getOrElse("default string if optionalobject is None")
Offutt answered 12/12, 2013 at 21:48 Comment(0)
L
25

For slightly nicer formatting that can span many lines (if you need to):

@optionalObject match {
  case Some(o) => {
    @o.field
  }
  case None => {
    No field text/html/whatever
  }
}

Or if you don't want to display anything if the field isn't defined:

@for(o <- optionalObject) {
  @o.field
}
Lactose answered 13/12, 2013 at 4:53 Comment(1)
That second code snippet for the display nothing if the field isn't defined use case is lovely. I keep on glossing over the fact that Option is a collection type, allowing you to do stuff like this.Dispersoid
O
6
@optionalobject.map(o => o.field).getOrElse("default string if optionalobject is None")
Offutt answered 12/12, 2013 at 21:48 Comment(0)
T
0

Judging by your tags you are using a Play 2.x variant, but you are referencing documentation from a module meant for Play 1.x.

Assuming your types match, I believe what you are looking for is something like:

@optionalobject.getOrElse(field)
Traveled answered 12/12, 2013 at 20:55 Comment(2)
This is not working. It is saying that the field does not exist. However, it must exist. When just output the case class it shows all of the fields of the case class.Thrasonical
@Lilluda5 Edit your question and show more of your code. How are you declaring optionalobject and field?Traveled
G
0

Another possibility is using map, syntax I prefer for mixing up with HTML

@pagination.next.map { next =>
  <a href="@Routes.paginated(next)">
    @HtmlFormat.escape("Next >>>")
  </a>
}
Guayaquil answered 31/5, 2017 at 13:17 Comment(0)
A
0

Sometimes it might be convenient to write a short helper when dealing with Option to declutter the template code:

  // Helper object is defined in some file Helper.scala
  object Helper {
    def maybeAttribute[T](attrName:String, maybeValue:Option[String]) = 
       maybeValue.fold("") { value => 
         Html(attrName + "=" + value).toString()
       }
  }

Then the template can use this helper method directly like

  // some view.scala.html file
  <div @Helper.maybeAttribute("id",maybeId)>
  </div>
Axillary answered 30/1, 2018 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.