Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on object.member in Play 2.0 templates

According to the Play 2.0 documentation, pattern matching can be done in a template like so:

@connected match {

  case models.Admin(name) => {
    <span class="admin">Connected as admin (@name)</span>
  }

  case models.User(name) => {
    <span>Connected as @name</span>
  }   
}

The text between the brackets after the case expressions is treated as output (e.g. HTML), and this is quite convenient.

However, when attempting to use a match expression that is not a simple variable, such as object.member, like this:

@album.year match {
   case Some(y: Int) => { @y }
   case None => { <b>nope</b> }
}

it results in a compilation error: "')' expected but 'case' found."

Using defining to bind the expression to a simple variable, like this:

@defining(album.year) { foo =>
  @foo match {
        case Some(y: Int) => { @y }
        case None => { <b>nope</b> }
      }
  }

works, but it seems a bit cumbersome.

Is there a proper way to use this pattern matching feature on expressions that involve an object and a member (e.g. album.year)?

like image 275
kes Avatar asked May 13 '12 05:05

kes


2 Answers

Have you tried this?

@album.year match {

   case Some(y: Int) => {
     @y 
   }
   case None => { 
     <b>nope</b> 
   }
}

See here for an example: https://github.com/bjartek/computer-database-mongo/blob/matchtest/app/views/list.scala.html#L67

It looks like whitespace is very important to get right when doing this in the template

like image 176
bjartek Avatar answered Oct 24 '22 04:10

bjartek


Not currently possible (in version 2.0.1), as it is a confirmed bug:

https://play.lighthouseapp.com/projects/82401/tickets/46-support-more-complex-match-statement

like image 1
kes Avatar answered Oct 24 '22 03:10

kes