play-2.5缓存与国际化

时间:2016-12-29 22:16:06

标签: scala caching internationalization playframework-2.5

我想在考虑语言的同时缓存控制器的响应。有了这个页面here on stackoverflow,我几乎可以做到一切正确,但是当我使用缓存并点击网页上的链接更改语言时,我遇到了一个问题:它不能直接使用:语言只有在我刷新页面后才会更改,当我在没有缓存的情况下尝试时它会完美运行。 cacheHelper:

package controllers
import play.api.cache.Cached
import play.api.Configuration
import play.api.mvc._
import javax.inject.{ Inject, Singleton }

@Singleton
class CacheHelper @Inject() (val cached: Cached)(implicit configuration: Configuration) {

  def apply(label: String, duration: Int)(action: EssentialAction) = {
    cached({ r: RequestHeader => label + "." + getLanguage(r) }, duration) { action }
  }

  def getLanguage(request: RequestHeader): String = {
    request.cookies.get("PLAY_LANG").map(_.value).getOrElse("fr")
  }
}

控制器:

package controllers
 import javax.inject._
import play.api.i18n._
import scala.concurrent.ExecutionContext
import play.api.mvc.{Action, Controller, EssentialAction, RequestHeader}
@Singleton
class ActuController @Inject() (val cacheHelper: CacheHelper, val messagesApi: MessagesApi)(implicit ec: ExecutionContext) extends Controller with I18nSupport {

  def index = cacheHelper("homePage", 60) {
    Action { implicit req =>
      cacheHelper.getLanguage(req) match {
        case "fr" => Ok("Bonjour le monde")
        case "ru" => Ok("привет")
        case _ => Ok("hello")
      }
    }
  }

}

我试图直接设置" PLAY_LANG" cookie而不是直接使用#withLang,但它也不起作用。有任何想法吗 ?感谢。

"语言转换器" :

package controllers


import play.api.mvc._
import play.api.i18n.{ MessagesApi, Messages, Lang }
import javax.inject.{ Inject, Singleton }

import play.api.cache.Cached
@Singleton
class Application @Inject() (val messagesApi: MessagesApi) extends Controller {

  def selectLang(lang: String) = Action { implicit request =>
    request.headers.get(REFERER).map { referer =>
      Redirect(referer).withLang(Lang(lang))

    }.getOrElse {
      Redirect(routes.Application.index).withLang(Lang(lang))

    }
  }
}

0 个答案:

没有答案