Created
July 8, 2011 14:35
-
-
Save bremac/1071973 to your computer and use it in GitHub Desktop.
Minimal template processor in JS.
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
| 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(''); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.');