adamduncan / eleventy-plugin-i18n

Eleventy plugin to assist with internationalization and dictionary translations
MIT License
103 stars 10 forks source link

Ability to customize the context locale (custom directory structure) #8

Open gremo opened 3 years ago

gremo commented 3 years ago

My directory structure doesn't have the folder named "it" (my default / fallback locale) because I'd like to not prefixing my default locale. The plugin, however, will complain about undefined locale,

[i18n] Could not find 'foo' in 'prodotti'. Using 'it' fallback.

Here the products is simple the page url (/prodotti).

I'll make a PR for it.

adamduncan commented 3 years ago

Interesting. This seems partly related to a suggestion from @unconfident re: localeContext.

I'm trying to get a better idea of how.

Can you please share an example of how you'd leverage the contextLocale function in your case?

gremo commented 3 years ago

Here is my configuration for your plugin:

  eleventyConfig.addPlugin(require('eleventy-plugin-i18n'), {
    translations: glob.sync('./translations/*.json')
      .map(pathname => ({ key: path.basename(pathname, '.json'), contents: require(pathname) }))
      .reduce((prev, curr) => ({...prev, [curr.key]: curr.contents }), {}),
    fallbackLocales: {
      '*': 'it'
    },
    contextLocale: (page, config) => {
      // Test if string starts with a locale prefix (i.e. /en/ or /fr/ with a leading slash)
      const isLocalizedUrl = /^\/([\w]{2})\//g.exec((page && page.url) || '');
      if (isLocalizedUrl) {
        return isLocalizedUrl[1];
      }

      // ... otherwise assume it's the fallback locale
      return config.fallbackLocales['*'];
    },
  });
gremo commented 3 years ago

@adamduncan any update on this? Have you seen my PR, what do you think?

adamduncan commented 3 years ago

Hey @gremo. We need to patch something else with the library (#10), so will try to absorb this properly when we do that 👍