Skip to content

Instantly share code, notes, and snippets.

@dfurber
Created June 13, 2011 20:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfurber/1023570 to your computer and use it in GitHub Desktop.
Save dfurber/1023570 to your computer and use it in GitHub Desktop.
Javascript Template Rendering Engine
# Template rendering in JS
# Combines John Resig's simple js templates with Sproutcore's content binding concept.
# Define your templates in the templates array (or rewrite it to work however you like!)
#
# To render a template to an html string, call:
# render('example', dataObject)
# OR
# render('example', arrayOfDataObjects)
# OR if you have template that isn't bound to a data object:
# render('static_example')
#
# If you want to jquerify the rendered HTML, so you can add event listeners before adding to the DOM:
# html = $ render('example', dataObject)
# $('#results').html html
#
# OR inject into the DOM directly.
# $('#results').append render('example', arrayOfDataObjects)
#
# OR use it without a defined template:
# render '<h2><%= content.name %></h2>', name: name
#
# Why use it?
# It abstracts your client-side view logic away from your behavior code.
# If you don't want to keep your templates in one file, you can replace the templates= part
# to define templates however you like. Or look at the first line of window.render where
# it looks for template, and replace with your own logic for finding a template to render.
do ->
templates =
example: '''
<li>
<h2><a href="<%= content.url %>"><%= content.name %></a></h2>
<% if (content.hasDetails) { %>
<p><%= content.details.join(', ') %></p>
<% } %>
</li>
'''
static_example: '''
<h2>Foobar</h2>
'''
templateCache = {}
# Simple JavaScript Templating
# John Resig - http://ejohn.org/ - MIT Licensed
window.tmpl = (str, data) ->
# Figure out if we're getting a template, or if we need to
# load the template - and be sure to cache the result.
if not /\W/.test(str)
fn = templateCache[str] = templateCache[str] or tmpl(document.getElementById(str).innerHTML)
else
# Generate a reusable function that will serve as a template
# generator (and which will be cached).
str = str.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
fn = new Function("content",
"var p=[],print=function(){p.push.apply(p,arguments);};p.push('#{str}');return p.join('');")
# Provide some basic currying to the user
return if data then fn( data ) else fn
window.render = (template, items) ->
template = templates[template] or template
if items
if _(items).isArray?()
html = ''
for item in items
html += tmpl(template, item)
return html
else
return tmpl(template, items)
else
return tmpl(template)
/*
The JS version of templates.coffee.
*/
(function() {
var templateCache, templates;
templates = {
example: '<li>\n <h2><a href="<%= content.url %>"><%= content.name %></a></h2>\n <% if (content.hasDetails) { %>\n <p><%= content.details.join(\', \') %></p>\n <% } %>\n</li>',
static_example: '<h2>Foobar</h2>'
};
templateCache = {};
window.tmpl = function(str, data) {
var fn;
if (!/\W/.test(str)) {
fn = templateCache[str] = templateCache[str] || tmpl(document.getElementById(str).innerHTML);
} else {
str = str.replace(/[\r\t\n]/g, " ").split("<%").join("\t").replace(/((^|%>)[^\t]*)'/g, "$1\r").replace(/\t=(.*?)%>/g, "',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'");
fn = new Function("content", "var p=[],print=function(){p.push.apply(p,arguments);};p.push('" + str + "');return p.join('');");
}
if (data) {
return fn(data);
} else {
return fn;
}
};
return window.render = function(template, items) {
var html, item, _base, _i, _len;
template = templates[template];
if (items) {
if (typeof (_base = _(items)).isArray == "function" ? _base.isArray() : void 0) {
html = '';
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
html += tmpl(template, item);
}
return html;
} else {
return tmpl(template, items);
}
} else {
return tmpl(template);
}
};
})();
@alexgorbatchev
Copy link

Thanks for this! Saved me some time :)

@justinSelf
Copy link

I dig it! Going to use it right now!

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