Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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"
}
};
@alesanabria

This comment has been minimized.

Copy link

alesanabria commented Jan 21, 2015

Thanks man work like charm!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.