Simple i18n for Single Page Apps

I recently made a little iOS app (about a dozen views) with Framework7 for the UI.

While Framework7 is awesome, I'm not using any templating engine since my app is quite small so I don't have a way to translate my app easily in different languages. The main language was English, but I wanted my app to be in French too.

I created two files : en.json and fr.json in a folder named i18n in the www folder of my Cordova project. Both files have the same strcture :

{
  "app": {
       "example_string": "English sentence"
   }
}
{
  "app": {
       "example_string": "Phrase en fran├žais"
   }
}

In the "app" key, I simply listed all strings I wanted to translate in my app.

When the app boots, I fetch the file corresponding to the device preferred language (en.json by default).

I decode the content of the file as a JSON value, and store it in a global variable named locale_dictionnary.

The two following functions help me to finally display the i18n values when needed:

function getLocale(locale_key) {
    if (locale_dictionnary[locale_key]) {
        return locale_dictionnary[locale_key]
    } else {
        console.log('missing_locale: ' + locale_key)
        return 'missing_locale: ' + locale_key
    }
}

function MountLocale() {
    var a = document.querySelectorAll('[data-locale]')
    for (var i in a) if (a.hasOwnProperty(i)) {
        var key = (a[i].getAttribute('data-locale'))
        if(a[i].placeholder) {
            a[i].placeholder = getLocale(key)
        }
        a[i].innerHTML = getLocale(key)
    }
}

So in order to display the strings in my HTML, I call the MountLocale() function on every page change. And my HTML is written with data attributes like this:

<span data-locale="example_string"></span>

It works with placeholders in input fields as well! You just need to have a placeholder attribute in your input tag (it can't be empty, just needs to be there).

This article is my 2nd oldest. It is 292 words long

© 2018 Stan Larroque. All rights reserved.