From bd408614685205e2c054c3206bf04a88523b77b1 Mon Sep 17 00:00:00 2001 From: Zach Leatherman Date: Wed, 27 Jul 2022 17:00:44 -0500 Subject: [PATCH] Using a dictionary library for i18n, also shows how to use i18n with navigation plugin. --- .eleventy.js | 15 +++++++++++++++ _includes/layouts/base.njk | 2 +- _includes/layouts/post.njk | 11 ++++++----- en/about/index.md | 5 +++-- en/blog.njk | 2 +- en/index.njk | 2 +- i18n.js | 22 ++++++++++++++++++++++ package.json | 5 +++-- 8 files changed, 52 insertions(+), 12 deletions(-) create mode 100644 i18n.js diff --git a/.eleventy.js b/.eleventy.js index 741af7f..87300af 100644 --- a/.eleventy.js +++ b/.eleventy.js @@ -1,9 +1,11 @@ const { DateTime } = require("luxon"); +const rosetta = require("rosetta"); const markdownItAnchor = require("markdown-it-anchor"); const pluginRss = require("@11ty/eleventy-plugin-rss"); const pluginSyntaxHighlight = require("@11ty/eleventy-plugin-syntaxhighlight"); const pluginNavigation = require("@11ty/eleventy-navigation"); const { EleventyI18nPlugin } = require("@11ty/eleventy"); +const languageStrings = require("./i18n.js"); module.exports = function(eleventyConfig) { eleventyConfig.ignores.add("README.md"); @@ -78,6 +80,19 @@ module.exports = function(eleventyConfig) { showVersion: true, }); + // i18n filter using Rosetta + const rosettaLib = rosetta(languageStrings); + + eleventyConfig.addFilter("i18n", function (key, lang) { + const I18N_PREFIX = "i18n."; + if(key.startsWith(I18N_PREFIX)) { + key = key.slice(I18N_PREFIX.length); + } + // depends on page.lang in 2.0.0-canary.14+ + let page = this.page || this.ctx?.page || this.context?.environments?.page || {}; + return rosettaLib.t(key, {}, lang || page.lang); + }); + return { // Control which files Eleventy will process // e.g.: *.md, *.njk, *.html, *.liquid diff --git a/_includes/layouts/base.njk b/_includes/layouts/base.njk index 8080fbd..c64ca83 100644 --- a/_includes/layouts/base.njk +++ b/_includes/layouts/base.njk @@ -30,7 +30,7 @@ {#- Read more about `eleventy-navigation` at https://www.11ty.dev/docs/plugins/navigation/ #} diff --git a/_includes/layouts/post.njk b/_includes/layouts/post.njk index 81c4f46..4395de1 100644 --- a/_includes/layouts/post.njk +++ b/_includes/layouts/post.njk @@ -18,7 +18,7 @@ templateClass: tmpl-post {% if i18nLinks.length %}