Skip to content

Instantly share code, notes, and snippets.

@livingston
Last active September 12, 2022 22:10
Show Gist options
  • Save livingston/9570969 to your computer and use it in GitHub Desktop.
Save livingston/9570969 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