How to let the user switch language in playframework 2
Asked Answered
S

2

7

In my play 1.x controller I had this:

public static void language(final String language){
    Lang.change(language);
    Header referer = request.headers.get("referer");
    if(referer == null){
        index();
    }else{
        redirect(referer.value());
    }
}

I would like to do the same in play 2.x but I have the impression that functionality is not available any more. This is what I have so far

  def language(language:String) = Action { implicit request =>

    // TODO change language

    val referer = request.headers.get("referer")
    referer.map{ referer =>
      Redirect(referer, FOUND);
    }getOrElse(
      Ok(views.html.index())
    )
  }
Simon answered 16/5, 2012 at 10:17 Comment(0)
M
3

According to the documentation, in Play 2.4, inside the controller you can do

ctx().changeLang(new Lang(Lang.forCode("fr")));

You need to have a file conf/messages.fr so the application can refer to it for the message. You can start from the messages.default file and put your own messages.

Meningitis answered 12/2, 2016 at 16:39 Comment(0)
T
5

You can store the language in the user session. You can find an example here

This question has already been asked on the Play Google group

Til answered 16/5, 2012 at 11:32 Comment(1)
in fact there is no such system so you have to implement the language cookie yourself and pass the language to the template, see this example: github.com/julienrf/chooze/blob/master/app/controllers/…Simon
M
3

According to the documentation, in Play 2.4, inside the controller you can do

ctx().changeLang(new Lang(Lang.forCode("fr")));

You need to have a file conf/messages.fr so the application can refer to it for the message. You can start from the messages.default file and put your own messages.

Meningitis answered 12/2, 2016 at 16:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.