2

我有这个 scala 模板,并希望使用 case 语句根据匹配的枚举值呈现不同的 html。

我的模板如下所示:

@(tagStatus: String)

 try {
   TagStatus.withName(tagStatus) match {
         case TagStatus.deployed => {<span class="label label-success">@tagStatus</span>}
         case TagStatus.deployedPartially => {<span class="label label-important">@tagStatus</span>}
         case TagStatus.deployedWithProblems => {<span class="label label-important">@tagStatus</span>}
     }
 } catch {
    {<span class="label label-important">??</span>}
 }

枚举看起来像这样:

object TagStatus extends Enumeration{
   val deployed = Value("deployed")
   val deployedWithProblems = Value("deployed_with_problems")
   val deployedPartially = Value("deployed_partially")     
}

当我运行它时,我得到:

Compilation error
')' expected but 'case' found.
In C:\...\statusTag.scala.html at line 8.
5        case TagStatus.deployed => {<span class="label label-success">@tagStatus</span>}
6        case TagStatus.deployedPartially => {<span class="label label-important">@tagStatus</span>}
7        case TagStatus.deployedWithProblems => {<span class="label label-important">@tagStatus</span>}
8    } 
9 } catch {
10    {<span class="label label-important">??</span>}
11 }

我不知道这个错误消息是什么意思。

为了编译这个简单的代码片段,我缺少什么?

谢谢!

4

2 回答 2

4

toString 与 match 不兼容,因此使用将字符串转换为枚举withName

你可以这样做 - 我不太确定 Play 语法:

TagsStatus.withName(tagStatus) match {
  case TagStatus.deployed => {<span class="label label-success">@tagStatus</span>}
  case TagStatus.deployedPartially => {<span class="label label-important">@tagStatus</span>}
  case TagStatus.deployedWithProblems => {<span class="label label-important">@tagStatus</span>}
  case _ => {<span class="label label-important">??</span>}
}

顺便说一句,关于使用小写变量名的 Scala 模式匹配存在一个常见的相关问题

于 2013-09-25T10:17:15.480 回答
3

您不必在这里使用 try ,只需匹配您的通配符(请参阅:http ://www.playframework.com/documentation/2.1.x/ScalaTemplateUseCases )。

@(tagStatus: String)

@tagStatus match {
    case TagStatus.deployed.toString => {<span class="label label-success">@tagStatus</span>}
    case TagStatus.deployedPartially.toString => {<span class="label label-important">@tagStatus</span>}
    case TagStatus.deployedWithProblems.toString => {<span class="label label-important">@tagStatus</span>}
    case _ => {<span class="label label-important">??</span>}
}
于 2013-07-27T09:40:21.620 回答