Skip to content

Instantly share code, notes, and snippets.

@aweijnitz
Last active August 29, 2015 14:04
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 aweijnitz/50a31be6311efb536a3d to your computer and use it in GitHub Desktop.
Save aweijnitz/50a31be6311efb536a3d to your computer and use it in GitHub Desktop.
Three-line Template Engine in Javascript for quick substitution of object properties into a string
/**
* A mini "template engine".
* Arguments:
* template - A string of looking like "Something {{variableName}} and {{nested.object.data}}"
* data - A Javascript object with properties to substitute into the template
*
* Returns:
* A string with the variables substituted with the corresponding properties from the data
*/
var applyTemplate = function(template, data) {
var re = /{{([^{}]+?)}}/g;;
while (match = re.exec(template)) // "Compile" template to javascript
template = template.replace("{{" + match[1] + "}}", "'+this." + match[1] + "+'");
return (new Function("return '" + template + "';")).apply(data);
}
var template = 'Hello {{name}}! The weather is {{day.weatherStatus}} today. It is a {{day.weatherStatus}} {{day.weekday}}';
var data = {
name: 'Anders',
day: {
weekday: 'Wednesday',
weatherStatus: 'sunny'
}
};
console.log(applyTemplate(template, data));
/////// TEST SUPPORT
function log(msg) {
console.log(msg);
}
function test(expected, actual) {
try {
return (new RegExp(expected)).test(actual) ? "PASS" : "FAIL";
} catch(ex) {
return "FAIL with error "+ex;
}
}
/////// TEST DATA
var template = 'Hello {{name}}! The weather is {{day.weatherStatus}} today. It is a {{day.weatherStatus}} {{day.weekday}}';
var data = {
name: 'Anders',
day: {
weekday: 'Wednesday',
weatherStatus: 'sunny'
}
};
/////// TESTS
var expected = "Hello Anders! The weather is sunny today. It is a sunny Wednesday";
log("TEST basic substitution => " + test(expected, applyTemplate(template, data)));
log("TEST empty tag => " + test("", applyTemplate("{{}}", {})));
log("TEST missing property => " + test("undefined", applyTemplate("{{date}}", {})));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment