Created
October 20, 2011 12:12
-
-
Save alexyoung/1301000 to your computer and use it in GitHub Desktop.
templates
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
/** | |
* Render templates. | |
* | |
* @param {String} The template to use `<p>Hello {{name}}</p>` | |
* @param {String} The data `{ name: 'Alex' }` | |
* @return {String} The rendered template | |
**/ | |
function template(t, d) { | |
return t.replace(/{{([^}]*)}}/g, function(m, f, p, a) { | |
return d[f] || ''; | |
}); | |
}; |
Nice, I never get tired of passing functions to replace
;)
note that if d[f] == false
it will replace with ''
in my case since I use (prop in data)? data[prop] : ''
it will return the data[prop]
even if null
or false
.
microTemplate.parse('{{foo}} / {{bar}}', {foo : false, bar: null}); // "false / null"
template('{{foo}} / {{bar}}', {foo : false, bar: null}); // " / "
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have a similar implementation: https://github.com/millermedeiros/MM_js_lib/blob/master/src/other/microTemplate.js