Play 2.4及以上版本中的语言选择器斯卡拉2.11.6 [英] Language selector in Play 2.4 & Scala 2.11.6
问题描述
我正在尝试使用语言选择器和本地化消息来实现此简单页面:
I'm trying to implement this simple page with a language selector and a localized message:
| ... en ... |▼|
|...en...|▼|
理想情况下,当用户更改语言时,页面应重新加载,其中包含更新的消息和其他选择的语言
Ideally when the user changes the language the page should reload with an updated message and a different selected language
| .... fr .... |▼|
|....fr....|▼|
但是我无法使它正常工作:页面保持不变,唯一改变的是PLAY_LANG cookie.
but I can't get this to work: the page stays the same and the only thing that changes is the PLAY_LANG cookie.
控制器
package controllers
import javax.inject.Inject
import play.api.mvc._
import play.api.i18n._
import play.api.data._
import play.api.data.Forms._
class Test @Inject() (val messagesApi: MessagesApi) extends Controller with I18nSupport {
def index = Action { implicit request =>
Ok(views.html.test())
}
def changeLanguage() = Action { implicit request =>
val referrer = request.headers.get(REFERER).getOrElse("/")
val form = Form("language" -> nonEmptyText)
form.bindFromRequest.fold(
errors => BadRequest(referrer),
language => Redirect(referrer).withLang(Lang(language))
)
}
}
模板
@()(implicit messages: Messages, lang: Lang)
@helper.form(action = routes.Test.changeLanguage()) {
<select name="language" style="width: auto;"> onchange="this.form.submit()">
@play.api.i18n.Lang.availables(play.api.Play.current).map { l =>
<option value="@l.code" @(if(lang.code.startsWith(l.code)) "selected")>@l.code</option>
}
</select>
<h1>@Messages("test.message")</h1>
}
任何帮助将不胜感激.
推荐答案
罪魁祸首是模板中的无意的额外>"符号:
The culprit was an unintentional extra ">" symbol inside the template:
v
<select name="language" style="width: auto;"> onchange="this.form.submit()">
^
此错字没有产生任何错误,但阻止了server.side代码的执行.
This typo didn't generate any error but prevented the server.side code from being executed.
我应该注意到cookie不再更改了(它最初是在无法更改语言的代码起作用并且当我最终使其起作用时,我必须在模板内部引入了错字).
I should have noticed that the cookie didn't get changed anymore (it did initially when the language-changing code was not working and when I finally got it to work I must have introduced the typo inside the template).
这篇关于Play 2.4及以上版本中的语言选择器斯卡拉2.11.6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!