Skip to content

Instantly share code, notes, and snippets.

@tracend
Last active October 16, 2018 18:11
  • Star 21 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tracend/3261055 to your computer and use it in GitHub Desktop.
Handlebars Localisation Helper #cc

Localisation extension for Handlebars.js

This helper uses a global "window.locale" object to translate the keywords to text strings.

Features:

  • Multi-language support
  • Keyword nesting
  • Automatically sets the language (from the browser properties)

Usage:

In your handlebars template, call the 'l10n' helper and include the keyword path as a string. Example:

{{l10n "errors.minFileSize"}}
// Handlebars Localisation Helper
// Source: https://gist.github.com/tracend/3261055
Handlebars.registerHelper('l10n', function(keyword) {
var lang = (navigator.language) ? navigator.language : navigator.userLanguage;
// pick the right dictionary (if only one available assume it's the right one...)
var locale = window.locale[lang] || window.locale['en-US'] || window.locale || false;
// exit now if there's no data
if( !locale ) return target;
// loop through all the key hierarchy (if any)
var target = locale;
var key = keyword.split(".");
for (i in key){
target = target[key[i]];
}
// fallback to the original string if nothing found
target = target || keyword;
//output
return target;
});
window.locale = {
"en-US": {
"errors": {
"maxFileSize": "File is too big",
"minFileSize": "File is too small",
"acceptFileTypes": "Filetype not allowed",
"maxNumberOfFiles": "Max number of files exceeded",
"uploadedBytes": "Uploaded bytes exceed file size",
"emptyResult": "Empty file upload result"
},
"error": "Error",
"start": "Start",
"cancel": "Cancel",
"destroy": "Delete"
}
};
@alesanabriav
Copy link

Thanks man work like charm!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment