Skip to content

Instantly share code, notes, and snippets.

@amirrustam
Forked from livingston/readme.md
Created December 24, 2015 01:25
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 amirrustam/bc1686354704801c60b7 to your computer and use it in GitHub Desktop.
Save amirrustam/bc1686354704801c60b7 to your computer and use it in GitHub Desktop.
Vanilla JavaScript Templates

Usage

var welcome_user = new Template('#{welcome} #{name}!!');

welcome_user.parse({ welcome: "Hello", name: "John" });
//returns "Hello John!!"

welcome_user.parse({ welcome: "Hola", name: "Peter" });
//returns "Hola Peter!!"

You can user your own modifier method to cutomize the values.

An example, localizing the values with custom modifier,

var locale = {
    en: {
        welcome: 'Hello'
    },
    fr: {
        welcome: 'Bonjour'
    }
};

var current_locale = 'en';
var welcome_user = new Template('#{welcome} #{name}!!');

welcome_user.modifier = function (match, key) {
    return locale[current_locale][key] || this[key];
}

welcome_user.parse({ name: "Michelle" });
//returns "Hello Michelle!!"

current_locale = 'fr';
welcome_user.parse({ name: "Marie" })
//returns "Bonjour Marie!!"
(function (global) {
var Template = function (str) {
this.template = str || '';
Object.defineProperties( this, {
modifier: {
writable: true,
value: this._modifier
}
});
return this;
}
Object.defineProperties( Template.prototype, {
_regex: {
writable: false,
value: /#{(((?!{).)*)}/g
},
_modifier: {
writable: false,
value: function ( match, key ) {
return this[key] || '';
}
},
parse: {
writable: false,
value: function (data) {
return this.template.replace(this._regex, this.modifier.bind(data));
}
}
});
global['Template'] = Template;
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment