Skip to content

Instantly share code, notes, and snippets.

@bremac
Created July 8, 2011 14:35
Show Gist options
  • Select an option

  • Save bremac/1071973 to your computer and use it in GitHub Desktop.

Select an option

Save bremac/1071973 to your computer and use it in GitHub Desktop.
Minimal template processor in JS.
var template = function(ctx, tpl) {
var accum = [], idx = 0;
while (true) {
var start = tpl.indexOf('{{', idx);
if (start < 0) break;
var end = tpl.indexOf('}}', start);
if (end < 0) break;
var str = tpl.slice(start+2, end);
str = str.replace(/(^\s+|\s+$)/g, '');
accum.push(tpl.slice(idx, start));
var r = ctx, path = str.split('.');
while (path.length > 0 && r !== undefined)
r = r[path.shift()];
if (r === undefined) r = '';
accum.push(r);
idx = end + 2;
}
accum.push(tpl.slice(idx));
return accum.join('');
}
@bremac
Copy link
Author

bremac commented Jul 8, 2011

This is less a templating language than an interpolation engine like sprintf. Example use:

context = { name: 'Brendan', day: new Date() };
template(context, 'Hello {{ name }}, good {{ day }} to you.');

"Hello Brendan, good Fri Jul 08 2011 11:40:08 GMT-0300 (ADT) to you."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment