Created
December 7, 2015 15:51
-
-
Save drKnoxy/7acd857faea502ddaf85 to your computer and use it in GitHub Desktop.
Simple javascript templating
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
/** | |
* 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