Web Components and Internationalization

While exploring Web Components for a current project, came to a halt when faced with the question of language versions of a component.

As advertised, Web Components are portable pieces that can be inserted into any project. Nevertheless, Web Components can be linked directly to a project, but why would you use them instead of using Vue, React or any server-side template language? These are questions I still have to answer myself.

But back to my initial problem: What about the internationalization of Web Components?

I found a blog post1 that goes much deeper, and from there I cobbled together my low effort version below.

The gist is, if you have a bunch of components with strings that can be translated, you handle them in the bundle and load external language files when the component starts up.

If you have a simple, single component, then you can add the language strings inside the component definition, query the document language <html lang="en"> or the navigator.language and be done with it. This is still not the most portable solution, but it works for that use case.

More complex implementation of that idea here: web-components/note-list.js at master · RolandDreger/web-components · GitHub

const FALLBACK_LANG = "en";

class MyBookmark extends HTMLElement {
  constructor() {
    super();
    this._saved = false;
  }
  getDocumentLang() {
        return (
            document.body.getAttribute("xml:lang") ||
            document.body.getAttribute("lang") ||
            document.documentElement.getAttribute("xml:lang") ||
            document.documentElement.getAttribute("lang") ||
            FALLBACK_LANG
        );
    }

  render() {
    const lang = this.getDocumentLang();
    const state = this._saved ? 'bookmarks.button.bookmarked' : 'bookmarks.button.bookmark';
    const messages = {
      'de': {
            'bookmarks.button.bookmark': 'merken',
            'bookmarks.button.bookmarked': 'gemerkt'
      },
      'en': {
            'bookmarks.button.bookmark': 'save',
            'bookmarks.button.bookmarked': 'saved'
      },
    };
    const html = `${messages[lang][state]}`;
  }
}