Skip to content

Internationalisation

Matt Smith edited this page Jan 24, 2020 · 2 revisions

The application uses i18next for translating content. Visit the website for more information and documentation https://www.i18next.com.

Enabling locales

The configuration for internationalisation is located in server/internationalisation.js.

To enable translations for a locale, add the ISO language code to the whitelist property e.g. to enable Welsh:

i18next
  .init({
    whitelist: ['en', 'cy'],
    ...
  })

Rendering static text

Instead of declaring static text directly in the view templates, localised strings are passed to the view at render. Translations are stored as JSON objects in the server/locales directory.

To render a localised string in a view:

1. Define the string in the appropriate JSON file

// server/locales/en/common.json
{
 ...
 "myLocalisedString": "A localised string"
}

2. Pass the string to the view as a variable

// routes/my-route-handler.js
const myRouteHandler = (req, res) => {
 ...
 res.render('my-template', {
   myLocalisedString: req.t('myLocalisedString')
 })
}

3. Reference the localised variable in the view template

// views/my-template.njk
<p>{{ myLocalisedString }}</p>

Translating blocks of content

Defining long blocks of content as localised strings is not always practical. To translate a long block of content it is easier to use the language variable available to all templates to include the correct template partial for the active locale:

// views/my-template.njk
{% include "locales/" + language + "/long-content-block.njk" %}

// views/locales/en/long-content-block.njk
<p>My static text for a long content block ...<p>

This approach allows content to be defined as blocks of HTML for individual locales.

Clone this wiki locally