Ok, let’s be honest. Current localization in ExtJS 5.x is a mess and everything but efficient at this time.
IMO, the best approach is to set everything outside. The approach I’m using is quite simple and is deeply inspired from a YAML approach (and next release of my class Lang/i8n class will support YAML directly).
The cons: only one : At this time, you cannot change the lang dynamically/on-the-fly. Language is set just before Main App starts.
The “YAM-inspired” implementation:
Ext.define('Lang',{
singleton : true
,config : {
currentLang : null,
defaultLang : 'fr'
}
// Here starts string declarations
,strings: {
'fr_FR' : {
desktop: {
map : "Carte"
}
,settings: {
stretch: "Ajuster/Etirer"
,wallpaper: "Fond d'écran"
,preview: "Aperçu"
,none: "Aucun"
}
}
,'us_US' : {
desktop: {
map : "Map"
}
,settings: {
stretch: "Stretch to fit"
,wallpaper: "Wallpaper"
,preview: "Preview"
,none: "None"
}
}
// end of string declarations
// shortcuts
,fr : 'fr_FR'
,en : 'us_US'
,us : 'us_US'
}
,getStrings: function(lang) {
if (!lang || !Ext.isDefined(this.strings[lang]))
lang=this.getDefaultLang();
if (Ext.isString(this.strings[lang])) // got an aliase
lang = this.strings[lang];
return Ext.isDefined(this.strings[lang])
? this.strings[lang]
: { };
}
// Do the translation
,t : function(label, lang) {
var path = label.toLowerCase().split('.'),
p = this.getStrings(lang); // strings
for (var i = 0; i<path.length; i++) {
if (Ext.isDefined( p[ path[i] ]))
p = p[ path[i] ];
else return '<<' + label + '>>'; // not found
}
return p;
}
,constructor : function(config) {
this.initConfig(config);
if (!this.getCurrentLang())
this.setCurrentLang( this.getDefaultLang());
}
});
var i18n = function(label, lang) { return Lang.t(label, lang); };
How to use it :
– in main app, add ‘Lang’ to requires (it Lang is in main directory)
requires: [
'Lang',
]
– set language : Lang.SetCurrentLang(‘en’) for example
– get a string : i18n(“settings.wallpaper”) or Lang.t(“settings.wallpaper”)
Improvements/ToDo List
- Import YAML or JSON directly as a lang file (ie not built-in)
- Change current language on the fly, without reloading
You must be logged in to post a comment.