gpt4 book ai didi

scala - play framework 2.3 无需额外请求即可更改模板语言

转载 作者:行者123 更新时间:2023-12-01 23:43:41 24 4
gpt4 key购买 nike

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

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

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

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

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

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

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

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

最佳答案

您应该将您的 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 特征中有一个 implicit conversion从对 lang 的隐式请求,编译器会提示不明确的隐式参数。

关于scala - play framework 2.3 无需额外请求即可更改模板语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30140551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com