Reputation: 1109
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.
Upvotes: 6
Views: 4679
Reputation: 433
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>
Upvotes: 0
Reputation: 3598
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>
}
Upvotes: 0
Reputation: 12850
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
}
Upvotes: 25
Reputation: 1723
@optionalobject.map(o => o.field).getOrElse("default string if optionalobject is None")
Upvotes: 6
Reputation: 3449
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)
Upvotes: 0