2013-07-27 23 views
2

我有這個scala模板,並希望使用case語句根據匹配的枚舉值呈現不同的html。枚舉的框架scala模板與case語句

我的模板看起來是這樣的:

@(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

的toString是不匹配兼容,所以使用withName

的字符串轉換爲枚舉你可以做到這樣的 - 我不太清楚播放的語法:

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 pattern matching with lower case variable names

2

你不必在這裏使用試試,只需要匹配你的通配符(參見: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>} 
} 
+1

這給我一個錯誤:穩定標識符要求,但models.TagStatus.notReadyForDeployment.toString找到。如果我在匹配大小寫語句中對字符串進行硬編碼,它會起作用,但這樣我就不會再幹了。 – nemoo

+0

與普通的Scala不同,每個case(在=>符號之後)的輸出必須用{}包裝,否則你會得到一個''case'預期但標識符被發現「的錯誤。 –