Skip to content

Instantly share code, notes, and snippets.

@alexyoung
Created October 20, 2011 12:12
Show Gist options
  • Save alexyoung/1301000 to your computer and use it in GitHub Desktop.
Save alexyoung/1301000 to your computer and use it in GitHub Desktop.
templates
/**
* 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] || '';
});
};
@millermedeiros
Copy link

@alexyoung
Copy link
Author

Nice, I never get tired of passing functions to replace ;)

@millermedeiros
Copy link

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