播放框架scala模板与枚举的case语句

时间:2013-07-27 08:42:46

标签: scala playframework playframework-2.0

我有这个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 }

我不知道此错误消息的含义。

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

谢谢!

2 个答案:

答案 0 :(得分:4)

toString与match不兼容,因此使用withName

将String转换为枚举

你可以这样做 - 我不太确定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>}
}

BTW有一个与Scala pattern matching with lower case variable names

有关的常见问题

答案 1 :(得分:3)

你不必在这里试试,只是你匹配的外卡(见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>}
}