So translators are annoying to use because you need to memorize strings like Translate("category", "short_code")
.
As I recently switched to WebStorm I though what good is autocomplete here. So I’ve developed a proof of concept where you can find translation strings using IDE autocomplete.
So this is the command I use to translate:
T.landing.welcome()
Why the ()
brackets? Because you can switch the language on the fly (when server sends emails for example):
T.emails.order.newOrder('es')
This makes me so happy. Here’s the code:
// The main object
T = {
// Default language
currentLocale: 'et',
// Initialization
init: (loc) => {
if (loc)
T.currentLocale = loc
T.convert(T)
},
// Converts {et: '', en: ''} objects
// into function(){ return localized string }
convert: (obj) => {
for (var prop in obj) {
let p = obj[prop]
if (p && p.hasOwnProperty('en')) {
// Encapsulate translations object to stop change next loop
obj[prop] = (function() {
var translations = obj[prop]
return function(lang) {
if (!lang) lang = T.currentLocale
return translations[lang]
}
})()
} else if (_.isObject(obj[prop]) && obj.hasOwnProperty(prop)) {
T.convert(obj[prop])
}
}
}
}
// The actual translations (spread across files)
T.order = {
form: {
nrPeople: {
et: 'Inimeste arv',
en: 'Number of People'
},
duration: {
et: 'Kestvus tundides',
en: 'Duration in hours'
}
}
}
// Start conversion proccess
T.init()
This is so good I couldn’t help but share. This must have been done before, but no Meteor i18n package I’ve seen does it.