RESTX i18n support
RESTX has some support for i18n (internationalization), aimed to be used in a SPA (single page application).
enabling i18n support
You need to add a dependency on
restx-i18n to enable RESTX support for i18n.
You can do that with the shell:
restx deps add io.restx:restx-i18n:0.34.1
RESTX i18n relies on a mechanism used to access internationalized messages accessed through a
Messages is something very similar to a standard Java
ResourceBundle (default implementation actually uses one underneath), so most of the documentation you can find for standard Java
ResourceBundle, except that the files are encoded in
UTF-8 (as everything in RESTX).
accessing Messages in RESTX app
When i18n is enabled your application benefits from a default
Messages component that can be injected in any of your components.
If you intend to use several
Messages instances, name it when you ask for injection:
This instance loads its messages from a
labels resource bundle at the root of your application classpath. So all you need to do to provide messages in this instance is to create a
labels.properties file in your
src/main/resources directory (if using default project layout). Then you can provide each locale using the
_XX suffix as with standard resource bundles.
accessing Messages from a REST client
by default the i18n module exposes the default
Messages instance through a REST API.
This REST API is intented to be used by a SPA, and supports only basic operations.
It relies on the request locale to supply the messages. This means that it will provide the translations based on the standard HTTP
Accept-Language header, and if not present it will use the default locale of the server.
You can access the default labels on
/i18n/labels.json where you will get the key / messages in json format.
You can also access them on
<script> tag in your SPA. This is interesting because by default
<script> loading is blocking, so you don’t have to deal with an async interpolation of you keys / labels in your application.
The default template is:
As you can see it simply assigns the labels in a global variable named
You can easily customize that by providing your own template as a named string in your RESTX app.
For instance in a module:
Message parameter interpolation
Another difference with standard Java resource bundle is that the
Here is an example of use:
which with following