eleventy-plugin-i18n-demo
eleventy-plugin-i18n-demo copied to clipboard
Lang switcher that checks for translated pages
Hey, Thanks for the tool.
I'm working on a site that is not fully translated into all the languages.. I'm guessing thats probably the case with others. I made a tweak to the https://github.com/adamduncan/eleventy-plugin-i18n-demo/blob/master/src/_includes/components/language-selector.njk to help cover this.
I started on a filter that will help build a language selector that only lists pages that have been translated.
Basically, it uses the locales from locales.js file and the all
collection to check if urls exist before giving the links.
It would be cool to have something like this built in to your plugin that could also take advantage of the fallback locale for pages at "root" (for example, in one site I have English as my root url, and other languages following the i18 structure.
Here's what I have so far -
eleventyConfig.addFilter("i18n_urls", (page, all, locale) => {
// get remaining locales
var remaining_locals = locales.map((x => { return x.url })).filter(x => {return x !== locale && x !== "en"});
var i18n_pages = []
var valid_urls = all.map(x => {return x.url})
return remaining_locals.map(x => {
var new_url = page.replace(locale,x);
if (valid_urls.indexOf(new_url) !== -1){
console.log("pushing ", new_url)
return {
"url": new_url,
"meta": locales.filter(y => {return y.url === x})[0]
}
}
}).filter(x => {return x !== undefined})
});
and basic usage:
{% set lang_groups = page.url | i18n_urls(collections.all, locale) %}
{% if lang_groups | length > 0 %}
<div class="navbar-item has-dropdown has-text-grey is-hoverable is-block">
<a class="navbar-link has-text-grey is-transparent py-0">
<span class="icon is-large">
<i class="fas fa-lg fa-globe"></i>
</span>
</a>
<div class="navbar-dropdown">
{% for page in lang_groups %}
<a class="navbar-item" href="{{ page.url }}">{{ page.meta.label }}
{% endfor %}
</div>
</div>
{% endif %}