RobL Vs

Background

Oooh....erb templates in javascript

Found this ERB for jQuery script this morning from Dan Webb

http://gist.github.com/211964

 1// ERB style templates for jQuery in hardly any code.
 2//
 3// Based on http://ejohn.org/blog/javascript-micro-templating/
 4// 
 5// A tiny and simple plugin to allow erb style template rendering within jQuery.
 6// 
 7// Make a template:
 8// 
 9// <script type="text/html" id="template1">
10// <% $.each(items, function(i, image) { %>
11//   <p><img src="<%= image.media.m %>" alt="<%= image.title %>"></p>
12// <% }); %>
13// </script>
14// 
15// Render the template into the dom with some data:
16// 
17// <script type="text/javascript">
18// jQuery(function($) {
19//   $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=jordan%20III&format=json&jsoncallback=?", function(data) {
20//     $('#test').render('template1', data);
21//   });
22// });
23// </script>
24//
25// Alternatively, you can load templates from files:
26//
27// $('#test').render('template.ejs', data);
28
29jQuery(function($) {
30  var cache = {};
31  
32  function compile(source) {
33    return new Function("obj",
34          "var p=[],print=function(){p.push.apply(p,arguments);};" +
35     
36          "with(obj){p.push('" +
37     
38          source
39            .replace(/[\r\t\n]/g, " ")
40            .split("<%").join("\t")
41            .replace(/((^|%>)[^\t]*)'/g, "$1\r")
42            .replace(/\t=(.*?)%>/g, "',$1,'")
43            .split("\t").join("');")
44            .split("%>").join("p.push('")
45            .split("\r").join("\\'")
46        + "');}return p.join('');");
47  }
48  
49  function load(template) {
50    if (!(/\W/).test(template)) {
51      return compile($("#" + template).html());
52    } else {
53      var source;
54    
55      $.ajax({
56        async: false,
57        url: template,
58        dataType: 'text',
59        success: function(data) {
60          source = data;
61        }
62      });
63    
64      return compile(source);
65    }
66  }
67  
68  $.template = function(template, data) {
69    var fn = cache[template] = cache[template] || load(template);
70    
71    if (data) return fn(data);
72  }
73  
74  $.fn.render = function(str, data) {
75    return this.each(function() {
76      $(this).html($.template(str, data));
77    });
78  };
79});