2013-04-08 92 views
2

我希望應用程序的用戶可以在我的play2(play 2.1.1,scala 2.10.1)web應用程序中更改語言。我在i18n的模板中使用了@ Messages.get(...)。更改播放框架中模板中文本的語言2.1.1

application.langs="en,ru" 
在application.conf

。我通過 「en」 或 「RU」,以這種方法:

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

路線:

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

模板一堆(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> 
... 

重定向後頁面,我用相同的語言看到它。 :(

我看了很多老回答:在我的模板隱語言參數不工作,與withLang(...)方法調用過於重定向或動作沒有一個很好的解決方案,以便長時間

+0

它應該使用'.withLang(...)'方法。你可以嘗試將'(implicit l:Lang)'改成'(implicit l:play.api.i18n.Lang)'和'@import play.i18n.Messages'到'@import play.api.i18n.Messages' ? – EECOLOR 2013-04-09 20:02:31

+0

@EECOLOR,它沒有工作 – Tolsi 2013-04-10 07:10:13

回答

5

我做了它的工作,所以有我的變化。在應用程序代碼(沒有請求實例玩不知道從哪裏得到與語言的cookie):

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

而且在模板(play.api.i18n自動進口):

@()(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> 
... 
+0

幹得好!然後,[這裏是一個更通用的解決方案](http://stackoverflow.com/questions/9629250/how-to-avoid-passing-parameters-everywhere-in-play2):你可以定義你對每個動作的隱式請求少代碼。 – 2013-04-10 13:34:34

+0

是否有可能避免在每個模板中寫入'implicit l:Lang'部分,並且只在main中定義它? – 2013-07-29 20:57:11

1

我有同樣的問題,並加入我自己的消息分辨率級在play.i18n一個

對於消息的分辨率,你可以在這裏有一個例子(在Java中):https://github.com/adericbourg/proto-poll/blob/dev/app/util/user/message/Messages.java#L76

而且我的控制器changeLang的方法打電話給:https://github.com/adericbourg/proto-poll/blob/dev/app/util/security/CurrentUser.java#L71

它不相信這是一個很好的解決方案(它需要更多的代碼,我是一個懶惰的傢伙),但它的工作原理。希望這可以幫助...

+0

我找到了一個更簡單的解決方案 – Tolsi 2013-04-10 07:48:27