Ali Seivani
Ali Seivani

Reputation: 551

Localization of static HTML with i18next (loading local json translation files)

My project is HTML only. I am not going to use node or react version.

I've tried default example that works fine

 <div id="output" />

<script src="https://unpkg.com/i18next/dist/umd/i18next.min.js"></script>
<script>
    i18next.init({
      lng: 'en',
      debug: true,
      resources: {
        en: {
          translation: {
            "key": "Hello World"
          }
        },
        de: {
          translation: {
            "key": "hello welt"
          }
        }
      }
    }, function(err, t) {
      // init set content
      updateContent();
    });

    function updateContent() {
      document.getElementById('output').innerHTML = i18next.t('key');
    }

    function changeLng(lng) {
      i18next.changeLanguage(lng);
    }

    i18next.on('languageChanged', () => {
      updateContent();
    });
</script>

but I can't figure out how to load local json files instead of placing all translations in the js. Do I have to install an additional plugin for loading json translation files?

and is this the correct way of targeting every string in HTML?

function updateContent() {
  document.getElementById("homeTitle").innerHTML = i18next.t("home.title");
  document.getElementById("homeSubtitle").innerHTML = i18next.t("home.subtitle");
}

is there a way to add an attribute to HTML string like

<h1 data-i18n="home.title"></h1>

to get the translation?

Upvotes: 0

Views: 820

Answers (1)

Zeno Dalla Valle
Zeno Dalla Valle

Reputation: 919

You could load them with fetch, running a bunch of promises. I wrote a sandbox code example for you in vanilla JS.

PS: Don't know why, but when you open code sandbox the code isn't executed well, you have to refresh the local preview to get it working (or you could try to open the preview from here), but I tested it via Live Server in my dev environment and it's working fine.

Upvotes: 1

Related Questions