Last active
August 29, 2015 14:04
-
-
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
This file contains hidden or 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
/** | |
* 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); | |
} |
This file contains hidden or 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 = '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)); |
This file contains hidden or 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
/////// 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