加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 在Play Framework 2.4.0中的I18n

发布时间:2020-12-16 18:31:09 所属栏目:安全 来源:网络整理
导读:这是我的路线文件: GET /:lang controller.Application.index(lang: String)GET /:lang/news controller.Application.news(lang: String) 请注意,所有这些都以/:lang开头. 目前,我编写Application.scala作为 def index(lang: String) = Action { implicit
这是我的路线文件:

GET /:lang      controller.Application.index(lang: String)
GET /:lang/news controller.Application.news(lang: String)

请注意,所有这些都以/:lang开头.

目前,我编写Application.scala作为

def index(lang: String) = Action {
  implicit val messages: Messages = play.api.i18n.Messages.Implicits.applicationMessages(
    Lang(lang),play.api.Play.current)
  Ok(views.html.index("title"))
}

通过这种方式,我必须编写与Action一样多的隐式消息.有没有更好的解决方案呢?

解决方法

通过Lang只是更简单的选择:

def lang(lang: String) = Action {
    Ok(views.html.index("play")(Lang(lang)))
}

//template
@(text: String)(implicit lang: play.api.i18n.Lang)
@Messages("hello")

您可以使用操作组合重用某些代码,定义包装的请求和操作:

case class LocalizedRequest(val lang: Lang,request: Request[AnyContent]) extends WrappedRequest(request)

def LocalizedAction(lang: String)(f: LocalizedRequest => Result) = {
    Action{ request =>
      f(LocalizedRequest(Lang(lang),request))
    }
}

现在您可以像这样重用LocalizedAction:

//template
@(text: String)(implicit request: controllers.LocalizedRequest)
@Messages("hello")

//controller
def lang(lang: String) = LocalizedAction(lang){implicit request =>
    Ok(views.html.index("play"))
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读