Language selector in Play 2.4 & Scala 2.11.6

此生再无相见时 提交于 2019-12-25 16:36:33

问题


I'm trying to implement this simple page with a language selector and a localized message:


|...en...|▼|

A message in english


Ideally when the user changes the language the page should reload with an updated message and a different selected language


|....fr....|▼|

Un message en français


but I can't get this to work: the page stays the same and the only thing that changes is the PLAY_LANG cookie.

controller

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))
    )
  }
}

template

@()(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>
}

Any help would be appreciated.


回答1:


request in action should be implicit.

def index = Action {
implicit request =>



回答2:


The culprit was an unintentional extra ">" symbol inside the template:

                                            v
<select name="language" style="width: auto;"> onchange="this.form.submit()">
                                            ^

This typo didn't generate any error but prevented the server.side code from being executed.

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).



来源:https://stackoverflow.com/questions/30824933/language-selector-in-play-2-4-scala-2-11-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!