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 (eg 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 (eg album.year )?


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


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


Have you tried just doing this?

@album.year.getOrElse("<b>None</b>");

Not sure if it is as simple as that, but it should work. See https://github.com/playframework/Play20/blob/master/samples/scala/computer-database/app/views/list.scala.html#L64

链接地址: http://www.djcxy.com/p/10736.html

上一篇: 严格的别名和std :: array与C

下一篇: Play 2.0模板中的object.member模式匹配