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

Fix parsing locale from context #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
22 changes: 19 additions & 3 deletions i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ const chalk = require('chalk');
const get = require('lodash.get');
const templite = require('templite');

// should match "/en/", "/en-US/", "/en_US/"
const contextLocaleRegex = /^\/([a-z]{2,}(?:[_-][a-z]{2,})?)\//i;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe maximum length for a segment should be limited to 2 exactly but there's a chance that somebody uses "eng" or "english" as their locale name so I left it as [...]{2,}


/**
* Parses string looking like a lang code from the beginning of the url or filePathStem
*
* @param {string} path
* @return {string|null}
* @private
*/
function getContextLocale(path) {
const match = contextLocaleRegex.exec(path || '');
return match && match[1];
}

module.exports = function (
key,
data = {},
Expand All @@ -17,12 +32,13 @@ module.exports = function (
} = 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 url = get(page, 'filePathStem') || '';
const contextLocale = typeof url === 'string' ? getContextLocale(url) : '';

const locale = localeOverride || contextLocale;

// Preferred translation
const translation = get(translations, `[${key}][${locale}]`);
const translation = locale == null ? undefined : get(translations, `[${key}][${locale}]`);

if (translation !== undefined) {
return templite(translation, data);
Expand Down