Skip to content

Instantly share code, notes, and snippets.

@andyexeter
Created March 20, 2017 20:45
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 andyexeter/8c641eb744c0570d8eab384f76e66316 to your computer and use it in GitHub Desktop.
Save andyexeter/8c641eb744c0570d8eab384f76e66316 to your computer and use it in GitHub Desktop.
Interpolates a handlebars-ish template
/**
* 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