Permalink
Browse files

added micro-templating to gloss

  • Loading branch information...
1 parent da366cc commit f84b9703cf96cceab65a5fab2cd5c56f39fd0c19 @aaronj1335 aaronj1335 committed Apr 17, 2012
Showing with 67 additions and 0 deletions.
  1. +1 −0 requirejs-config.json
  2. +9 −0 src/require/test/template.mtpl
  3. +19 −0 src/require/test/test_tmpl.js
  4. +38 −0 src/require/tmpl.js
View
@@ -1,4 +1,5 @@
{
"paths": {
+ "tmpl": "./require/tmpl"
}
}
@@ -0,0 +1,9 @@
+<div>
+ <span><%= data.foo.bar %></span>
+ <span>length: <%= data.list.length %></span>
+ <ul>
+ <% for (var i = 0; i < data.list.length; i++) { %>
+ <li><%= data.list[i] %></li>
+ <% } %>
+ </ul>
+</div>
@@ -0,0 +1,19 @@
+/*global test, asyncTest, ok, equal, deepEqual, start, module, strictEqual */
+require([
+ 'path!vendor:jquery',
+ 'path!gloss:tmpl!require/test/template.mtpl'
+], function($, tmpl) {
+ test('template plugin compiled', function() {
+ ok(tmpl);
+ var data = {
+ foo: {bar: 'baz'},
+ list: ['uno', 'dos', 'tres']
+ },
+ $html = $(tmpl(data));
+ equal($html.find('li').length, 3);
+ equal($html.find('span:first').text(), data.foo.bar);
+ ok(/uno.*dos.*tres/.test($html.find('ul').text()));
+ });
+ start();
+});
+
View
@@ -0,0 +1,38 @@
+// storediq micro-templating
+//
+// inspired by John Resig's micro-templating:
+//
+// http://ejohn.org/blog/javascript-micro-templating/
+//
+// tweaked by Atanas Korchev (github: akorchev):
+//
+// https://gist.github.com/860240
+//
+// modified to work as a require.js plugin for storediq's client-side and build
+// infrastructure
+define(function() {
+ var compile = function(str) {
+ var value = "var out = ''; out+=" + "'" +
+ str.replace(/[\r\t\n]/g, " ")
+ .replace(/'(?=[^%]*%>)/g,"\t")
+ .split("'").join("\\'")
+ .split("\t").join("'")
+ .replace(/<%=(.+?)%>/g, "'; out += $1; out += '")
+ .split("<%").join("';")
+ .split("%>").join("out+='") +
+ "'; return out;";
+ return new Function("data", value);
+ };
+
+ return {
+ load: function(name, req, load) {
+ var url = req.toUrl(name);
+ console.log('name to url:',url);
+ req(['text!' + req.toUrl(name)], function(templateText) {
+ load(compile(templateText));
+ });
+ }
+ };
+});
+
+

0 comments on commit f84b970

Please sign in to comment.