0.5.0 • Published 12 months ago

eleventy-i18n v0.5.0

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
12 months ago

i18n for Eleventy

eleventy-i18n offers a translation dictionary, dynamic parameters, and pluralization support to create multilingual websites with ease.

Installation

npm install eleventy-i18n --save-dev

Translation files

Initially, incorporate your translation files into your project, for example:

// translations/en.json
{
  "hello": "Hello!"
}

// translations/fr.json
{
  "hello": "Bonjour !"
}

Plugin setup

Next, integrate the built-in Eleventy i18n plugin along with this plugin by adding them to the .eleventy.js file:

const { EleventyI18nPlugin } = require("@11ty/eleventy");
const i18nPlugin = require("eleventy-i18n");

const en = require("./src/translations/en.json");
const fr = require("./src/translations/fr.json");

module.exports = function (eleventyConfig) {
  // code...

  eleventyConfig.addPlugin(EleventyI18nPlugin, {
    defaultLanguage: "en",
    filters: {
      url: "locale_url",
      links: "locale_links"
    },
    errorMode: "strict"
  });

  eleventyConfig.addPlugin(i18nPlugin, {
    translations: { en, fr }
  });
};

Translation filter t

You can then make use of the t filter to translate the key into the desired language, as demonstrated below:

<p>{{ 'hello' | t }}</p>

Translation parameters

Your translations may also include parameter, as illustrated in the following example:

// translations/en.json
{
  "welcome": "Welcome {{ name }}!"
}

// translations/fr.json
{
  "welcome": "Bienvenue {{ name }} !"
}
<p>{{ 'welcome' | t({ name: 'John' }) }}</p>

Parameters may also be objects:

// translations/en.json
{
  "Hello, {{ user.name }}!"
}
<p>{{ 'welcome' | t({ user: { name: 'John' }}) }}</p>

Overriding the current locale

You have the option to enforce translation in a specific language, rather than relying on the current language setting:

<p>{{ 'hello' | t({}, 'fr') }}</p>

Additional configuration options

The plugin offers two optional configuration parameters:

  • fallbackLanguageTag: Specifies the fallback locale when a translation is not available for the current locale.
  • keySeparator: Enables the use of nested translations.
eleventyConfig.addPlugin(i18nPlugin, {
  translations: { en, fr },
  fallbackLanguageTag: 'en',
  keySeparator: '.'
});

Keep in mind that if you have a locale such as fr-CA, the plugin will first attempt to fallback to fr before resorting to the default locale you specified.

Here's an example illustrating the use of nested translations, made possible by the keySeparator configuration:

// translations/en.json
{
  "welcome": {
    "hello": "Hello!"
  }
}
<p>{{ 'welcome.hello' | t }}</p>
0.5.0

12 months ago

0.4.0

1 year ago

0.3.0

1 year ago

0.2.0

1 year ago

0.1.0

1 year ago