Skip to content

Instantly share code, notes, and snippets.

@wheresrhys
Created January 20, 2013 21:46
Show Gist options
  • Save wheresrhys/4581989 to your computer and use it in GitHub Desktop.
Save wheresrhys/4581989 to your computer and use it in GitHub Desktop.
Simple templating engine
var Template = function() {
var pattern = /\{{([\w-]+)\}}/g,
replacements = {
"\\" : "\\\\",
"\\r\\n": "\n",
"'": "\'",
"\"":"\\\""
},
cleanupRX = function() {
temp = [];
for(key in replacements) {
temp.push(key);
}
return RegExp("(?:(" + temp.join(")|(") + "))", "g");
}();
function cleanupHtml(str) {
return str.replace(cleanupRX, function() {
for(var i = 1, il = arguments.length - 2;i<il; i++) {
if( arguments[i] ) {
return replacements[arguments[i]];
}
}
});
}
function Template(str) {
this.html = cleanupHtml(str);
this._compile()
};
Template.prototype = {
_compile: function () {
this.apply = function (words) {
function substitute(match, key) {
return words[key] || "";
}
return this.html.replace(pattern, substitute)
}
},
set: Template
};
return Template
}();
var template = new Template("{{animal}}s only eat {{food}} and don't like {{fear}}");
template.apply({
animal: "bee",
food: "badgers",
fear: "honey"
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment