From 68830cadff90b3940ff3ac19707659adbaea725c Mon Sep 17 00:00:00 2001 From: Chris Williams Date: Tue, 27 Oct 2009 09:05:49 -0400 Subject: [PATCH] Updated the render_segment to allow for the same variable to be reused for multiple template segments. Added a map function that can be used if not available on array natively - ahem IE ahem --- examples/reuse_of_enumerables.html | 8 ++++++++ examples/reuse_of_enumerables.js | 6 ++++++ examples/reuse_of_enumerables.txt | 8 ++++++++ mustache.js | 21 +++++++++++++++++++-- 4 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 examples/reuse_of_enumerables.html create mode 100644 examples/reuse_of_enumerables.js create mode 100644 examples/reuse_of_enumerables.txt diff --git a/examples/reuse_of_enumerables.html b/examples/reuse_of_enumerables.html new file mode 100644 index 0000000..cc0cb7a --- /dev/null +++ b/examples/reuse_of_enumerables.html @@ -0,0 +1,8 @@ +{{#terms}} + {{name}} + {{index}} +{{/terms}} +{{#terms}} + {{name}} + {{index}} +{{/terms}} diff --git a/examples/reuse_of_enumerables.js b/examples/reuse_of_enumerables.js new file mode 100644 index 0000000..543e121 --- /dev/null +++ b/examples/reuse_of_enumerables.js @@ -0,0 +1,6 @@ +var reuse_of_enumerables = { + terms: [ + {name: 't1', index: 0}, + {name: 't2', index: 1}, + ] +}; \ No newline at end of file diff --git a/examples/reuse_of_enumerables.txt b/examples/reuse_of_enumerables.txt new file mode 100644 index 0000000..ec5b333 --- /dev/null +++ b/examples/reuse_of_enumerables.txt @@ -0,0 +1,8 @@ +t1 + 0 +t2 + 1 +t1 + 0 +t2 + 1 \ No newline at end of file diff --git a/mustache.js b/mustache.js index 7dc75a6..4de34d1 100644 --- a/mustache.js +++ b/mustache.js @@ -50,14 +50,15 @@ var Mustache = function() { return template; } var that = this; + // CSW - Added "+?" so it finds the tighest bound, not the widest var regex = new RegExp(this.otag + "\\#(.+)" + this.ctag + - "\\s*([\\s\\S]+)" + this.otag + "\\/\\1" + this.ctag + "\\s*", "mg"); + "\\s*([\\s\\S]+?)" + this.otag + "\\/\\1" + this.ctag + "\\s*", "mg"); // for each {{#foo}}{{/foo}} section do... return template.replace(regex, function(match, name, content) { var value = that.find(name, context); if(that.is_array(value)) { // Enumerable, Let's loop! - return value.map(function(row) { + return that.map(value, function(row) { return that.render(content, that.merge(context, that.create_context(row))); }).join(''); } else if(value) { // boolean section @@ -206,6 +207,22 @@ var Mustache = function() { */ trim: function(s) { return s.replace(/^\s*|\s*$/g, ''); + }, + + /* + Why, why, why? Because IE. Cry, cry cry. + */ + map: function(array, fn) { + if (typeof array.map == "function") { + return array.map(fn) + } else { + var r = []; + var l = array.length; + for(i=0;i