How to let the user switch language in playframewo

2019-02-22 03:11发布

问题:

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())
    )
  }

回答1:

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.



回答2:

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