Skip to content

Instantly share code, notes, and snippets.

@anasnakawa
Last active October 13, 2015 07:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anasnakawa/4159834 to your computer and use it in GitHub Desktop.
Save anasnakawa/4159834 to your computer and use it in GitHub Desktop.
parse a given template and repalce any variables wrapped withing brackets
// parse a given template and repalce any variables wrapped with brackets '{' & '}' with the
// corresponding object found in the passed context param
// * **param:** {string} template sting template to be parsed
// * **param:** {object} context object containing variables to inject into the template
//
// e.g: parse( 'hello my name is {name}, I am a {title}', {
// name: 'Anas Nakawa'
// title: function() {
// return 'software developer'
// }
// });
// >> 'hello my name is Anas Nakawa, I am a software developer'
var parse = function(template, context) {
return template.replace(/\{(.+?)\}/g, function(token, match){
if( !match in context ) {
throw new Error( 'cannot find a variable with the name {match} in template {template}'.replace(/{match}/, match).replace(/{template}/, template) );
}
return ( typeof context[match] === 'function' ) ? context[match]() : context[match];
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment