· 7 years ago · Oct 22, 2018, 04:54 AM
1// By default, Underscore uses ERB-style template delimiters, change the
2// following template settings to use alternative delimiters.
3_.templateSettings = {
4evaluate : /<%([\s\S]+?)%>/g,
5interpolate : /<%=([\s\S]+?)%>/g,
6escape : /<%-([\s\S]+?)%>/g
7};
8
9// JavaScript micro-templating, similar to John Resig's implementation.
10// Underscore templating handles arbitrary delimiters, preserves whitespace,
11// and correctly escapes quotes within interpolated code.
12_.template = function(str, data) {
13var c = _.templateSettings;
14var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
15'with(obj||{}){__p.push(\'' +
16str.replace(/\\/g, '\\\\')
17.replace(/'/g, "\\'")
18.replace(c.escape, function(match, code) {
19return "',_.escape(" + code.replace(/\\'/g, "'") + "),'";
20})
21.replace(c.interpolate, function(match, code) {
22return "'," + code.replace(/\\'/g, "'") + ",'";
23})
24.replace(c.evaluate || null, function(match, code) {
25return "');" + code.replace(/\\'/g, "'")
26.replace(/[\r\n\t]/g, ' ') + "__p.push('";
27})
28.replace(/\r/g, '\\r')
29.replace(/\n/g, '\\n')
30.replace(/\t/g, '\\t')
31+ "');}return __p.join('');";
32var func = new Function('obj', tmpl);
33return data ? func(data) : func;
34};