如何将隐式Action val覆盖到Play框架2中

时间:2013-01-26 11:00:56

标签: scala playframework playframework-2.0

我需要在传递给模板之前覆盖隐式值,但是不知道如何。 像这样:

/* This Session User and City setup */

case class MySession(user: Option[User] = None, city: Option[City] = None) {}


/* Trait for Controllers */

trait CMySession {
    implicit def mySession[A](implicit request: Request[A]) : MySession = {
        val userOpt = /*... get from session user here ...*/
        val cityOpt = /*... get from session city here ...*/
        MySession(user = userOpt, city = cityOpt)
    }
}


/* Controller */

def showCity(city_name: String) = Action { implicit request =>
    // Get city
    val cityOpt = { for (c <- mySession.city) yield Some(c) } getOrElse Cities.getByName(city_name)
    // Check if NO City in session, but we get it from request
    if (mySession.city != cityOpt) {
       // NEED some how override implicited mySession value here for template?!
    }
    Ok(views.html.showCity())
}}

感谢您提供任何线索!

1 个答案:

答案 0 :(得分:3)

Scala中隐式值的优点在于,您可以通过在范围中声明自己的隐式值(在if块中的情况下)或通过显式传递它来覆盖它们(在您的情况下是模板,例如{ {1}})。