Created
March 20, 2017 20:45
-
-
Save andyexeter/8c641eb744c0570d8eab384f76e66316 to your computer and use it in GitHub Desktop.
Interpolates a handlebars-ish template
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
/** | |
* Converts a handlerbars-ish template to HTML. | |
* Only supports scalar value access within an object. | |
* | |
* e.g: interpolate('<h1>{{title}}</h1>', {title: 'Hello World'}); | |
* | |
* @param {string} template The handlebars-ish template. | |
* @param {object} data Data object with which to parse the template. | |
* @returns {string} The interpolated string. | |
*/ | |
function interpolate(template, data) { | |
return template.replace(/{{\s*([^}\s]+)\s*}}/g, function (match, capture) { | |
if (typeof data[capture] === 'undefined') { | |
return ''; | |
} | |
return data[capture]; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment