Dealing with Options in Scala Play Template

Viewed 4379

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.

5 Answers

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