Skip to content

Internationalization

Sven Kubiak edited this page Jul 27, 2018 · 1 revision

Translations in mangoo I/O are based on the standard Locale of Java.

The Locale is determined from a specific i18n cookie or, as default, from each request from the Accept-Language header of the request. If the Locale can not be determined from the request or the cookie, the default language of the application from application.yaml will be used. If this configuration is not set, mangoo I/O will default to “en”.

If you want to force the language, you simply set the Locale in a filter – see Filters for more information on filters.

Locale.setDefault(Locale.ENGLISH);

You can set a locale cookie by using the CookieBuilder in one of your controllers.

public Response localize() {
    Cookie cookie = CookieBuilder.create()
            .name(Default.COOKIE_I18N_NAME.toString())
            .value("en")
            .build();

    return Response.withOk().andCookie(cookie);
}

Accessing translated values

mangoo I/O offers you a convenient way of accessing translations. To get hold of the translations simply inject the Messages class.

package controllers;

import com.google.inject.Inject;

import io.mangoo.i18n.Messages;
import io.mangoo.routing.Response;

public class I18nController {

    @Inject
    private Messages messages;

    public Response translation() {
        messages.get("my.translation");
        messages.get("my.othertranslation", "foo");
        ...
    }
}

The messages class offers you two methods of retrieving translations from the resource bundle. In this example a translation is called with and without passing optional parameters. The corresponding translation entries in the resource bundle would look like this

my.translation=This is a translation
my.othertranslation=This is a translation with the parameter: {0}
Note the {0} which will be replaced by the passed parameter "foo".

Translation in templates

To access translation in a template, you can us a special tag a long with the key for your translation.

${i18n("my.translation")}

To pass a parameter to the translation simply append the parameter

${i18n("my.othertranslation", "foo")}

If no key is found in the resource bundle the template will output an empty value.