Skip to content

Instantly share code, notes, and snippets.

@josher19
Created January 15, 2010 02:03
Show Gist options
  • Save josher19/277712 to your computer and use it in GitHub Desktop.
Save josher19/277712 to your computer and use it in GitHub Desktop.
/** Adding underscores template to the String object */
// Source: http://github.com/documentcloud/underscore
var _ = self._ || {};
// JavaScript templating a-la ERB, pilfered from John Resig's
// "Secrets of the JavaScript Ninja", page 83.
// Single-quote fix from Rick Strahl's version.
_.template = function(str, data) {
var fn = new Function('obj',
'var p=[],print=function(){p.push.apply(p,arguments);};' +
'with(obj){p.push(\'' +
str.replace(/[\r\t\n]/g, " ")
.replace(/'(?=[^%]*%>)/g,"\t")
.split("'").join("\\'")
.split("\t").join("'")
.replace(/<%=(.+?)%>/g, "',$1,'")
.split("<%").join("');")
.split("%>").join("p.push('")
+ "');}return p.join('');");
return data ? fn(data) : fn;
};
// Then you can either provide a context:
var str = "The <%= b.join('') %> jumps over the <%= a %>";
var c = _.template(str, {
a : "dog",
b : ['f','o','x']
})
// Or use global scope (self or this):
a = "dog";
b = ['f','o','x'];
str = "The <%= b.join('') %> jumps over the <%= a %>";
var c = _.template(str, self);
// To make it easier to use, you can add it to the String prototype:
String.prototype.template = function(context) { return _.template(this, context || self); }
// and call it like this:
"The <%= a %> jumps over the <%= b.join('') %>!".template()
// to use global variables, or:
"The <%= a %> jumps over the <%= b.join('') %>!".template({ a: "cow", b: ['m','o','o','n' ]})
// to use variables from a context.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment