Last active
          October 13, 2015 07:18 
        
      - 
      
- 
        Save anasnakawa/4159834 to your computer and use it in GitHub Desktop. 
    parse a given template and repalce any variables wrapped withing brackets
  
        
  
    
      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
    
  
  
    
  | // 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