【问题标题】:play framework 2.3 change template language without extra requestplay framework 2.3 更改模板语言无需额外请求
【发布时间】:2015-05-09 13:34:08
【问题描述】:

更改语言的正常方法是使用

进行重定向响应
.withLang(Lang(newLangCode))

但是在没有额外重定向的情况下如何更好地更改当前语言,我有以下构造。如果用户没有语言,我会尝试使用用户记录或请求 cookie 或标头中的语言。

def index(userId:Int) = Action {
val userLang = getUser(userId).getLang.getOrElse(implicitly[Lang])
Ok(views.html.index(...)).withLang(userLang)
}

但是这种方法当然行不通:views.html.index(...) 是用旧的隐式 lang 调用的,而“withLang”只为新请求设置 cookie。

我只知道一种解决方案:使用显式语言参数调用模板函数。

def index(userId:Int) = Action {
   implicit request => 
   val userLang = getUser(userId).getLang.getOrElse(implicitly[Lang])
   Ok(views.html.index(...)(request,userLang)).withLang(userLang)
}

但可能存在更规范的方式来进行语言切换?

【问题讨论】:

  • 我不知道 Play 本身是否有更简洁的方式,但是手动提供一个值来覆盖不适当的范围内隐式感觉就像换出隐式的规范方式

标签: scala cookies playframework playframework-2.3


【解决方案1】:

您应该将您的 userLang 值声明为隐式。这样,您的userLang 值将自动为您的模板参数@(...)(implicit lang: Lang) 拾取。

def index(userId:Int) = Action { request => 
    implicit val userLang = getUser(userId).getLang.getOrElse(implicitly[Lang])
    Ok(views.html.index(...)).withLang(userLang)
}

您还需要从请求参数中删除隐式修饰符,因为在 Controller trait 中有一个从隐式请求到 lang 的 implicit conversion,编译器会抱怨隐式参数不明确。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    相关资源
    最近更新 更多