Created
January 20, 2013 21:46
-
-
Save wheresrhys/4581989 to your computer and use it in GitHub Desktop.
Simple templating engine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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