Native JavaScript Multilanguage Templating
In the project I’m currently working on, I faced the “problem” to integrate multilanguage support, but due to the fact that the new app should be written in vanilla JS, without any plugins, libraries or other dependencies, I had to develop my own localization layer. In this article I want to show you my approach on this…
My solution is based on a template system that I implemented into my project at an earlier stage. If you are interested in how this works, I recommend you read my article Utilize a repository of reusable ES6 template literals.
Let’s start with the standard scaffold of an HTML5 app, extended with some style
‘s, an initialization script
and a lonely main
element, we want to fill with some localized content:
1 |
|
The script
points to the following ES6 module class in the file app.js:
1 | class App { |
Nothing uncommon so far, if you are familiar with ES6 classes and imports/exports.
Now let’s create a localizations.js file, to store the needed localized strings in all wanted languages. Every language will have its own branch in a Localizations
object, represented by its two-letter ISO-639-1 language code. All translations are accessible via an unique english key word:
1 | export function Localizations() { |
As we import the localizations.js in our app.js, we can initialize the localizations in the constructor of the app class with the language code of the users browser:
1 | import { Localizations } from './localizations.js'; |
app.localization
now holds the key/value list of the current language.
Now we implement the templating class, as described in Utilize a repository of reusable ES6 template literals and define a first template called helloWorld
…
1 | class Templates { |
The inner text of the h1
element in the helloWorld
template refers to the globally available variable app.localization
, we initialized in the last step, and points to the translation helloWorld
.
In app.js we import the templates.js and implement some code in the init
method, to get the template and bring it to the DOM:
1 | import { Localizations } from './localizations.js'; |
This is it …
In the following Github repository you will find a solution based on this example, extented with a language selector, cookie support and some helper methods to keep the code nice and clean:
https://github.com/kristofzerbe/Native-JavaScript-Multilanguage-Templating
You can interact with this article (applause, criticism, whatever) by mention it in one of your posts, which will be shown here as a Webmention, or by leaving a good old comment with your GitHub account.
Webmentions
No Webmentions yet...
In case your blog software can't send Webmentions, you can use this form to submit me a mention of this article...
Comments