【发布时间】:2012-05-13 05:21:29
【问题描述】:
根据Play 2.0 documentation,模式匹配可以在模板中完成,如下所示:
@connected match {
case models.Admin(name) => {
<span class="admin">Connected as admin (@name)</span>
}
case models.User(name) => {
<span>Connected as @name</span>
}
}
case 表达式后括号之间的文本被当作输出(例如 HTML),这很方便。
但是,当尝试使用不是简单变量的匹配表达式时,例如 object.member,像这样:
@album.year match {
case Some(y: Int) => { @y }
case None => { <b>nope</b> }
}
它会导致编译错误:
"')' expected but 'case' found."
使用defining 将表达式绑定到一个简单的变量,如下所示:
@defining(album.year) { foo =>
@foo match {
case Some(y: Int) => { @y }
case None => { <b>nope</b> }
}
}
有效,但似乎有点麻烦。
在涉及对象和成员的表达式(例如album.year)上使用此模式匹配功能是否有适当的方法?
【问题讨论】:
-
是否匹配 @(album.year { case Some(y: Int) => { @y } case None => { nope } }) 或 @(album. year) match { case Some(y: Int) => { @y } case None => { nope } } 有效吗?
-
不,这些都不起作用。第一个导致“预期的定义开始”,第二个导致与上述相同的“')'预期...”错误。
-
@{album.year match { case Some(y: Int) => { @y } case None => { nope } }} 有效吗?
-
不,同样的结果(“预期的定义开始”)。
-
感谢临时解决方法。它似乎已打补丁,但尚未发布稳定版本。
标签: templates scala playframework pattern-matching playframework-2.0