Documentation

You are viewing the documentation for the 2.3.9 release in the 2.3.x series of releases. The latest stable release series is 3.0.x.

§Externalising messages and internationalization

§Specifying languages supported by your application

To specify your application’s languages, you need a valid language code, specified by a valid ISO Language Code, optionally followed by a valid ISO Country Code. For example, fr or en-US.

To start, you need to specify the languages that your application supports in its conf/application.conf file:

application.langs="en,en-US,fr"

§Changing language

To permanently change the user language, use the changeLang() method:

Controller.changeLang("cs");

The new value will be saved to the user’s language cookie.

§Externalizing messages

You can externalize messages in the conf/messages.xxx files.

The default conf/messages file matches all languages. You can specify additional language messages files, such as conf/messages.fr or conf/messages.en-US.

You can retrieve messages for the current language using the play.i18n.Messages object:

String title = Messages.get("home.title")

You can also specify the language explicitly:

String title = Messages.get(new Lang(Lang.forCode("fr")), "home.title")

Note: If you have a Request in the scope, it will provide a default Lang value corresponding to the preferred language extracted from the Accept-Language header and matching one of the application’s supported languages. You should also add a Lang implicit parameter to your template like this: @()(implicit lang: Lang).

§Use in templates

@import play.i18n._
@Messages.get("key")

§Formatting messages

Messages are formatted using the java.text.MessageFormat library. For example, if you have defined a message like this:

files.summary=The disk {1} contains {0} file(s).

You can then specify parameters as:

Messages.get("files.summary", d.files.length, d.name)

§Notes on apostrophes

Since Messages uses java.text.MessageFormat, please be aware that single quotes are used as a meta-character for escaping parameter substitutions.

For example, if you have the following messages defined:

info.error=You aren''t logged in!
example.formatting=When using MessageFormat, '''{0}''' is replaced with the first parameter.

you should expect the following results:

String errorMessage = Messages.get("info.error");
Boolean areEqual = errorMessage.equals("You aren't logged in!");
String errorMessage = Messages.get("example.formatting");
Boolean areEqual = errorMessage.equals("When using MessageFormat, '{0}' is replaced with the first parameter.");

§Retrieving supported languages from an HTTP request

You can retrieve a specific HTTP request’s supported languages:

public static Result index() {
  return ok(request().acceptLanguages());
}

Next: The application Global object