Skip to main content

Internationalisation

Availability

Ships in the release after 0.8.0.

Translations live in plain .properties files on the classpath, read as UTF-8:

# src/main/resources/messages.properties
greeting=Hello, {0}!
cart.items=You have {0,number,integer} items

# src/main/resources/messages_es.properties
greeting=¡Hola, {0}!
cart.items=Tienes {0,number,integer} artículos
app.register(Messages.class, Messages.bundle("messages"))
.use(LocaleMiddleware.builder()
.supported(Locale.ENGLISH, Locale.forLanguageTag("es"), Locale.forLanguageTag("pt-BR"))
.queryParam("lang") // ?lang=es wins over the header
.cookie("lang") // e.g. set by a language picker
.build());

app.get("/hello/{name}", ctx -> ctx.text(ctx.message("greeting", ctx.pathParam("name"))));

How the locale is chosen​

  1. the query parameter, if configured and supported;
  2. the cookie, if configured and supported;
  3. the best match for Accept-Language (es-MX → es, pt → pt-BR);
  4. the first supported locale.

The response says which language it is in (Content-Language) and that it depends on Accept-Language (Vary), so caches keep the translations apart. Without the middleware, ctx.locale() is the first language of Accept-Language, or the JVM's default.

Messages​

  • Arguments use MessageFormat for the locale: {0,number}, {1,date,long}, {2,choice,0#no items|1#one item|1<{2} items}. A single quote starts a quoted section, so write '' for an apostrophe.
  • A key missing in messages_es.properties falls back to messages.properties; a key missing everywhere renders as the key itself, so a forgotten translation shows on the page instead of failing the request.
  • In templates, pass ctx.message(...) results in the model, or the Messages object itself.