Skip to content

Instantly share code, notes, and snippets.

@phalkunz
Last active August 29, 2015 14:05
Show Gist options
  • Save phalkunz/db87cc5cb03c0ee274b5 to your computer and use it in GitHub Desktop.
Save phalkunz/db87cc5cb03c0ee274b5 to your computer and use it in GitHub Desktop.
A really simple template function
/**
* A really simple template function.
*
* USAGE:
*
* 1. Ivoke `prepareTemplate(template)` by provide template string as an argument
* 2. The above invocation returns another function which called by with data argument
**/
function prepareTemplate(template) {
return function(data) {
var matches = template.match(/(?!\{\{)[a-zA-Z0-9_-]+(?=\}\})/g);
var output = template;
for(var i = 0; i <= matches.length; i++) {
output = output.replace('{{' + matches[i] + '}}', data[matches[i]]);
}
return output;
};
}
/**
* Example
**/
var compile = prepareTemplate("Hello, I am {{name}}. I'm from {{country}}.");
compile({ 'name': 'Jonn', 'country': 'New Zealand' }); // Hello, I'm John. I'm from New Zealand.
compile({ 'name': 'Phalkun', 'country': 'Cambodia'}); // Hello, I'm Phalkun. I'm from Cambodia.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment