Last active
August 29, 2015 14:05
-
-
Save phalkunz/db87cc5cb03c0ee274b5 to your computer and use it in GitHub Desktop.
A really simple template function
This file contains 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
/** | |
* 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