Working with options in Scala Playlist template

I am trying to use a type type reference in my Scala Play template. I tried to use this resource: http://www.playframework.com/modules/scala-0.9/templates

This is how I try to refer to a field in the case class:

@{optionalobject ?. field} 

and it does not work, this is the error I get:

 ';' expected but '.' found. 

I am not sure why I am getting this error.

+6
source share
5 answers
 @optionalobject.map(o => o.field).getOrElse("default string if optionalobject is None") 
+5
source

For more convenient formatting, which 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 do not want to display anything if the field is not defined:

 @for(o <- optionalObject) { @o.field } 
+21
source

Judging by your tags, you are using the Play 2.x option, but referring to the documentation from the module intended for Play 1.x.

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

 @optionalobject.getOrElse(field) 
0
source

Another possibility is to use the map, the syntax I prefer for mixing with HTML

 @pagination.next.map { next => <a href="@Routes.paginated(next)"> @HtmlFormat.escape("Next >>>") </a> } 
0
source

Sometimes itโ€™s convenient to write a short helper when working with Option to declare 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() } } 

The template can then use this helper method directly, as

  // some view.scala.html file <div @Helper.maybeAttribute("id",maybeId)> </div> 
0
source

All Articles