Skip to content

Instantly share code, notes, and snippets.

@drKnoxy
Created December 7, 2015 15:51
Show Gist options
  • Save drKnoxy/7acd857faea502ddaf85 to your computer and use it in GitHub Desktop.
Save drKnoxy/7acd857faea502ddaf85 to your computer and use it in GitHub Desktop.
Simple javascript templating
/**
* Simple template rendering
* + double curly brace syntax {{id}} or {{ id }}
* + only supports rendering, no conditions or expressions
* + no error checking
*
* @param {string} tmpl Your template string
* @param {obj} data The data to inject
* @return {string}
*/
function render(tmpl, data) {
var curlyBraceRegex = /{{([^}}]+)}}/g
var finds = tmpl.match(curlyBraceRegex);
finds.forEach(function(curlyProp) {
var prop = curlyProp.replace('{{', '').replace('}}','').trim();
if (data[prop]){
tmpl = tmpl.split(curlyProp).join(data[prop]);
}
});
return tmpl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment