Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the ability to customize the context locale #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,12 @@ fallbackLocales: {

👀 `eleventy-plugin-i18n` will warn you in the Node console when the intended translation or fallback values can't be found for a given language based on your `translations` data.

#### `contextLocale`

Type: `function` | Default: ‌`(page, config) => get(page, 'url', '').split('/')[1]`

You might provide a function in order to compute the context locale (that is, the locale applied to the `i18n` filter when no arguments are provided). By default, this would be the first segment of the URL (`/en/`, `/it/` and so on). If you use a custom directory strategy, like not prefixing the current locale, this option comes to help. The first argument of the function is the `page` object (could be `undefined`), the second is the plugin `config` object.

## Usage

Once configured, the `i18n` [Universal filter](https://www.11ty.dev/docs/filters/#universal-filters) is available throughout Nunjucks, Handlebars, Liquid, and JavaScript templates and includes. E.g. To return the translation for our `hello` key in Nunjucks or Liquid syntax:
Expand Down
8 changes: 4 additions & 4 deletions i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ module.exports = function (
) {
const {
translations = {},
fallbackLocales: fallbackLocales = {}
fallbackLocales: fallbackLocales = {},
contextLocale: contextLocale = page => get(page, 'url', '').split('/')[1]
} = pluginOptions;

// Use explicit `locale` argument if passed in, otherwise infer it from URL prefix segment
const url = get(page, 'url', '');
const contextLocale = url.split('/')[1];
const locale = localeOverride || contextLocale;
// (or use the provided function to compute it)
const locale = localeOverride || contextLocale(page, pluginOptions);

// Preferred translation
const translation = get(translations, `[${key}][${locale}]`);
Expand Down