Controller:
def test = Action { implicit request =>
import play.api.i18n._
val msg = Messages(\"error.invalid\")
implicit val langInController
The play.api.i18n.Messages(key)
function takes an additional implicit parameter of type Lang
. So when you write Messages("foo")
it is expanded to Messages("foo")(l)
, where l
is a value of type Lang
taken from the current implicit scope.
There’s always an available default implicit lang (which has a low priority), using your jvm default locale.
But when you are inside a Controller, an implicit value with a higher priority can be found if there is an implicit request. This value looks in the Accept-Language
header of the request.
When you are inside a template, the default implicit lang will be used unless your template imports another implicit lang.
That’s why, in your example, messages computed from the Controller use the Accept-Language
request header and messages computed from the View use your jvm default locale.
If you add an implicit parameter of type Lang
to your template, this parameter will have a higher priority than the default lang and will be used to compute messages:
@(langInController: Lang, msg:String)(implicit request: RequestHeader, lang: Lang)
<div>Lang from controller: @langInController, Message: @msg</div>
<div>Message from view: @Messages("error.required")</div>
When you’ll call the template from a Controller action, its implicit lang will be passed, so the same lang will be used by both your Views and your Controllers.