Search code examples
playframeworklocale

How to override the default locale for current request / response


Working with your typical web application, and I am having issues with enforcing the locale I want the Play Framework 2.4 Messages API to use, when answering requests (and rendering views).

What I have tried is calling Http.Context.Implicit.ctx().changeLang(mySpecificLangCode); from my Controller (extends devkit.mvc.Controller). If I call play.i18n.Messages#get(java.lang.String, java.lang.Object...) after that, the answer I get is in the language I want, everything is fine.
If I use the Messages API from my views (scala / Twirl) for servicing the same request, it is not okay, though. It falls back to the default language. I have to wait for the client to send a second request for it to be served with the right language.
I think this is because the first time, the server sends the PLAY_LANG cookie, the client sends that in the following requests and somehow this tells Play to render the view with the language I want. I cannot rely on this behavior, though, because I have to consider the client lifespan is a single request. I have no control on the client and I don't / can't base my code on the client request's Accept-Language header either. I have tried debugging things a bit and looking at what happens when the Messages API is called from inside the view, reading some docs, it didn't help me much, even less so considering I am not fluent in scala.

The recommendations (here at SO and from the official docs too) seems to be to use dependency injection to provide a Messages object to views, but I cannot affort to modify my views (my response uses a scala template, which calls other templates etc. modifying all of them is out of question).

What can I do, is what I want to do plainly and simply not feasible without modifying the views ?


Solution

  • I eventually found out this is (was) an actual issue in the Play Framework, see https://github.com/playframework/playframework/issues/5875 (with a workaround that sort of works).