templatesplayframework-2.0

match case in scala template doesn't work, in play2


My code in scala template:

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

But the case ... be displayed directly to the generated html page:

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

And In the generated .template.scala, it's:

"""
<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>
"""

But I see in the doc, it should support the match case: https://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

Finally, I found a way to work:

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

But it looks so complicated.

UPDATE2

Find another simple solution:

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

But it doesn't work well in complex case:

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

The @routes.Users.logout won't be converted.

UPDATE3

This is a getOrElse solution:

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

It works but it doesn't use match case


Solution

  • I was hitting the same problem. Enclosing the right part of the case in curly braces fixed the issue for me.

    This works for me:

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

    Without the braces, it gave an error with the space after the { on the match line highlighted. "'case' expected but identifier found."

    I also gives me that error if I try to put an @ before the opening curly brace like this:

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