I would like to cache a response of a controller while considering the language. With this page here on stackoverflow I was able to make almost everything right but I have one problem when I use the cache and click on a link on the webpage to change the language : it doesn't work directly : the language changes only after I refresh the page and it works perfectly when I try without the cache. The 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")
}
}
the controller :
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")
}
}
}
}
I have tried to set directly a "PLAY_LANG" cookie instead of using #withLang directly but it doesn't work either. Any ideas ? Thanks.
the "language changer" :
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))
}
}
}