Created
January 19, 2012 00:56
-
-
Save jethrolarson/1636901 to your computer and use it in GitHub Desktop.
Mod of _.template binds `this` to the element passed in, and adds <%@varname%> as a handy shortcut to <%=this.varname%>
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
| //OVERWRITING Underscore.js's templates | |
| // By default, Underscore uses ERB-style template delimiters, change the | |
| // following template settings to use alternative delimiters. | |
| _.templateSettings = { | |
| evaluate : /<%([\s\S]+?)%>/g, | |
| interpolate : /<%=([\s\S]+?)%>/g, | |
| escape : /<%-([\s\S]+?)%>/g | |
| value : /<%@([\s\S]+?)%>/g // inserts value of a variable on the object or "" if undefined | |
| }); | |
| // JavaScript micro-templating, similar to John Resig's implementation. | |
| // Underscore templating handles arbitrary delimiters, preserves whitespace, | |
| // and correctly escapes quotes within interpolated code. | |
| // Jethro adds context binding to data and `value` template delimeter | |
| var tIndex = 0; | |
| _.template = function(str, data) { | |
| var c = _.templateSettings; | |
| var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' + | |
| '(function(){with(obj||{}){__p.push(\'' + | |
| str.replace(/\\/g, '\\\\') | |
| .replace(/'/g, "\\'") | |
| .replace(c.escape, function(match, code) { | |
| return "',_.escape(" + code.replace(/\\'/g, "'") + "),'"; | |
| }) | |
| .replace(c.value, function(match, code) { | |
| return "',this." + code.replace(/\\'/g, "'") + "||'','"; | |
| }) | |
| .replace(c.interpolate, function(match, code) { | |
| return "'," + code.replace(/\\'/g, "'") + ",'"; | |
| }) | |
| .replace(c.evaluate || null, function(match, code) { | |
| return "');" + code.replace(/\\'/g, "'") | |
| .replace(/[\r\n\t]/g, ' ') + ";__p.push('"; | |
| }) | |
| .replace(/\r/g, '\\r') | |
| .replace(/\n/g, '\\n') | |
| .replace(/\t/g, '\\t') | |
| + "');}}).call(obj);return __p.join('');//@ sourceURL=template"+(tIndex++)+".js"; | |
| var func = new Function('obj', '_', tmpl); | |
| return data ? func(data, _) : function(data) { return func(data, _) }; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment