I'm currently working on the conversion of a huge Flex application to Angular 2.
Flex uses text files containing key/value pairs for localization (i18n).
In order to convert those to JSON, I've created a simple automating tool which allows dropping multiple text files and automatically converts the data to JSON.
I've made this tool available online with some useful properties to control the JSON output structure. Feel free to give it a try:
https://amirch1.github.io/blog/text2json/
When creating a SPA (Single Page Application), many times we like it to be localization-ready,
meaning it can be easily translated to other languages.
Without getting into the many aspects of localization (and sometimes internationalization),
I would like to present a simple way to localize HTML elements using HTML5 "data-" attribute.
The idea is to add a key attribute to the HTML element that we want to localize.
For example:
<span data-key="txt1"></span>
We then create a JSON file holding all the application text as key-value pairs. For example:
{
"txt1": "translated text 1",
"txt2": "translated text 2",
"txt3": "translated text 3"
}
For each language we create a separate JSON file.
When the application loads, we use jQuery to load and parse the JSON file.
Then we access each HTML element by its data-key and set its HTML to the corresponding value from the JSON data file:
var appNS;
(function (appNS) {
appNS.initApp = function(){
// load language file
$.getJSON('en_us.json', function(data) {
// json loaded - save to object
appNS.Lang = data;
for (var key in appNS.Lang)
$('[data-key="'+key+'"]').html(appNS.Lang[key]);
});
}
} (appNS = appNS || {}));
$(document).ready(function () {
appNS.initApp();
});
In this example, I've also used a name space and a JavaScript module.
A working demo can be seen in this plnkr.