Skip to content

Instantly share code, notes, and snippets.

@lokothodida
Created July 15, 2015 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lokothodida/aa7ee1fbcfecbe364ec9 to your computer and use it in GitHub Desktop.
Save lokothodida/aa7ee1fbcfecbe364ec9 to your computer and use it in GitHub Desktop.
jQuery Simple Internationalization (i18n) Support
// This snippet shows how to add simple internationalization (i18n)
// functionality to your jQuery plugin
// The concept is general enough to apply to any library and not just jQuery
// This is based slightly on how elFinder does its i18n functionality
;(function($, window, document, undefined) {
// Create your plugin on the $.fn namespace
// We are using @plugin as an alias so that we can attach properties to it
// later on without having to do $.fn.plugin.propertyName etc
var plugin = $.fn.plugin = function(options) {
// Initialize the settings using the defaults (which we define later)
var settings = $.extend(plugin.defaults, options);
// Define our i18n function
var i18n = function(key, replacements) {
// Set the language
var lang = settings.lang;
// Pick out the correct dictionary and get the corresponding string
var dict = plugin.i18n[lang] || plugin.i18n[plugin.defaults.lang];
var string = dict[key];
// If any replacements have been defined, replace all '$1', '$2', ...
// placeholders in the order of the @replacements array
if (replacements) $.each(replacements, function(idx, replacement) {
var placeholder = '$' + (idx + 1);
string = string.replace(placeholder, replacement);
});
return string;
};
// Rest of your plugin, where you can now use i18n with the languages that
// are registered with the plugin
// E.g. var title = i18n('TITLE')
// var errorMsg = i18n('ERROR', [someErrorBasedVariable])
};
// Default plugin options
// Since these are publicly exposed on $.fn.plugin, people using the plugin can
// modify the default settings to their likings
plugin.defaults = {
lang: 'en', // Seems sensible to make 'language' an option in this case
// ...
};
// Initialize i18n dictionary set
plugin.i18n = {};
// Our first dictionary
plugin.i18n.en = {
'TITLE' : 'Title',
'SUBTITLE' : 'Subtitle',
'ERROR' : 'There was an error processing $1!',
// All the strings you want ...
};
})(jQuery, window, document);
// Now when people want to add their own language sets to your plugin, they
// can just create their own files that extend the @plugin.i18n object
// E.g. jquery.plugin.de.js might look like this:
;(function($, window, document, undefined) {
// Sorry if these are inaccurate: this was done just using Google Translate
$.fn.plugin.i18n.de = {
'TITLE' : 'Titel',
'SUBTITLE' : 'Untertitel',
'ERROR' : 'Es gab einen Fehler Verarbeitung $1!',
// And all the other strings ...
};
})(jQuery, window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment