2012-03-17 59 views
27

我在斯卡拉模板代碼:比賽情況斯卡拉模板不工作,play2

@session.get("user.id") match { 
    case Some(_) => "xx" 
    case _ => "yy" 
} 
<a href="">Logout</a> 

case ...直接顯示生成的HTML頁面:

match { case Some(_) => "xx" case _ => "yy" } Logout 

,並在產生.template.scala,它是:

""" 
<body> 
"""),_display_(Seq(/*11.4*/session/*11.11*/.get("user.id"))),format.raw/*11.26*/(""" match """),format.raw("""{"""),format.raw/*11.34*/(""" 
    case Some(_) => "xx" 
    case _ => "yy" 
"""),format.raw("""}"""),format.raw/*14.4*/(""" 
<a href="">Logout</a> 
""" 

但我看到的文檔,它應該支持match casehttps://github.com/playframework/Play20/wiki/ScalaTemplates

@connected match { 

    case models.Admin(name) => { 
    <span class="admin">Connected as admin (@name)</span> 
    } 

    case models.User(name) => { 
    <span>Connected as @name</span> 
    } 

} 

UPDATE1

最後,我找到了一個工作方式:

@defining(session.get("user.id")) { x => 
    @x match { 
     case Some(_) => { "xx" } 
     case None => {"yy"} 
    } 
} 

但它看起來那麼複雜。

UPDATE2

找到另一種簡單的解決方案:

@{session.get("user.id") match { 
    case Some(_) => "xx" 
    case _ => "yy" 
}} 

但它不能在複雜的情況下正常工作:

@{session.get("user.id") match { 
    case Some(_) => {<a href="@routes.Users.logout">Logout</a>} 
    case _ => "yy" 
}} 

@routes.Users.logout不會被轉換。

UPDATE3

這是一個getOrElse解決方案:

@session.get("user.id").map { _ => 
    <a href="@routes.Users.logout">Logout</a> 
}.getOrElse { 
    Not logged 
} 

它的工作原理,但它不使用match case

+0

如果將括號中的正確部分括起來怎麼辦?例如。''一些(_)=> {「xx」}' – 2012-03-17 09:08:23

+0

謝謝,但那不起作用 – Freewind 2012-03-17 09:40:49

回答

47

我被擊中了同樣的問題。將案件的正確部分用花括號括起來解決了我的問題。

這個工作對我來說:

@user match { 
    case Some(user) => { Welcome, @user.username! } 
    case None => { <a href="@routes.Application.login">Login</a> } 
} 

如果沒有括號,它的空間給了一個錯誤之後{在比賽行高亮顯示。 「預計會發現'病例',但找到標識符。」

我也給我的錯誤,如果我試圖在大括號這樣前放一個@:

//This gives me the same error 
@user match { 
    case Some(user) => @{ "Welcome, " + user.username + "!" } 
    case None => { <a href="@routes.Application.login">Login</a> } 
} 
+0

注意:空格和\ n格式化代碼的花式使用可能也會觸發相同的錯誤我遇到類似於\ @users match { case Some(users)=> {\ n @for(\ n user < - users \ n){\ n \ @ user.name \ n} } – ilmirons 2015-01-30 12:51:19

0

我找到了一種方法來解決:

 <div class="col-md-9"> 
     @{ 
      articles collect { 
      case (title,time,shortcontent) => { 
      Html(s""" 
       <div class="blog-post"> 
        <h2 class="blog-post-title"> $title </h2> 
        <p class="blog-post-meta"> $time </p> 
        <p> $shortcontent </p> 
        <hr/> 
       </div> 
      """) 
      } 
     } 
     } 
    </div> 

的想法是返回一個字符串,然後使用Html方法將其轉換。