Change language of text in template in play framework 2.1.1

夙愿已清 提交于 2019-12-08 01:36:26

问题


I want the user of the application can change the language in my play2 (play 2.1.1, scala 2.10.1) web application. I use @Messages.get(...) in my templates for i18n.

I have

application.langs="en,ru"

in application.conf. I pass "en" or "ru" to that method:

def index = Action {
   Ok(views.html.index())
}

def changeLanguage(lang:String) = Action {
  implicit request =>
    Logger.logger.debug("Change user lang to : " + lang)
    val referrer = request.headers.get(REFERER).getOrElse(HOME_URL)
    Redirect(referrer).withLang(Lang(lang))
}

routes:

GET     /                           controllers.Application.index
GET     /index                      controllers.Application.changeLanguage(lang ?= "ru")

the template bunch (views.html.index):

@()(implicit l: Lang)

@import play.i18n.Messages

...

<a href="/about">@Messages.get("about")</li>

...

<a href="index?lang=ru" id="ru"></a>
<a href="index?lang=en" id="en"></a>
...

After redirecting the page, I see it on the same language. :(

I was read many old answers: implicit language parameter in my template does not work, redirect or action with withLang(...) method call too. Did not have a good solution so long time?


回答1:


I made it work, so there are my changes. In app code (without an request instance play does not know where to get the cookie with the language?):

def index = Action {
 implicit request=>
   Ok(views.html.index())
}

And in the template (play.api.i18n imports automatically):

@()(implicit l: Lang)

...

<a href="/about">@Messages("about")</li>

...

<a href="index?lang=ru" id="ru"></a>
<a href="index?lang=en" id="en"></a>
...



回答2:


I had the same issue and added my own message-resolution class over the play.i18n one.

For message resolution, you can have a example here (in Java): https://github.com/adericbourg/proto-poll/blob/dev/app/util/user/message/Messages.java#L76

And my controller changeLang's method calls this: https://github.com/adericbourg/proto-poll/blob/dev/app/util/security/CurrentUser.java#L71

It do not believe it is a good solution (it requires more code and I'm a lazy guy) but it works. Hope this can help...



来源:https://stackoverflow.com/questions/15888330/change-language-of-text-in-template-in-play-framework-2-1-1

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