Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save explodingcamera/59aea15203c4ed731042 to your computer and use it in GitHub Desktop.
Save explodingcamera/59aea15203c4ed731042 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"
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment