Skip to content

Commit 68830ca

Browse files
author
Chris Williams
committed
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
1 parent 638094e commit 68830ca

File tree

4 files changed

+41
-2
lines changed

4 files changed

+41
-2
lines changed

examples/reuse_of_enumerables.html

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{{#terms}}
2+
{{name}}
3+
{{index}}
4+
{{/terms}}
5+
{{#terms}}
6+
{{name}}
7+
{{index}}
8+
{{/terms}}

examples/reuse_of_enumerables.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
var reuse_of_enumerables = {
2+
terms: [
3+
{name: 't1', index: 0},
4+
{name: 't2', index: 1},
5+
]
6+
};

examples/reuse_of_enumerables.txt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
t1
2+
0
3+
t2
4+
1
5+
t1
6+
0
7+
t2
8+
1

mustache.js

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,14 +50,15 @@ var Mustache = function() {
5050
return template;
5151
}
5252
var that = this;
53+
// CSW - Added "+?" so it finds the tighest bound, not the widest
5354
var regex = new RegExp(this.otag + "\\#(.+)" + this.ctag +
54-
"\\s*([\\s\\S]+)" + this.otag + "\\/\\1" + this.ctag + "\\s*", "mg");
55+
"\\s*([\\s\\S]+?)" + this.otag + "\\/\\1" + this.ctag + "\\s*", "mg");
5556

5657
// for each {{#foo}}{{/foo}} section do...
5758
return template.replace(regex, function(match, name, content) {
5859
var value = that.find(name, context);
5960
if(that.is_array(value)) { // Enumerable, Let's loop!
60-
return value.map(function(row) {
61+
return that.map(value, function(row) {
6162
return that.render(content, that.merge(context, that.create_context(row)));
6263
}).join('');
6364
} else if(value) { // boolean section
@@ -206,6 +207,22 @@ var Mustache = function() {
206207
*/
207208
trim: function(s) {
208209
return s.replace(/^\s*|\s*$/g, '');
210+
},
211+
212+
/*
213+
Why, why, why? Because IE. Cry, cry cry.
214+
*/
215+
map: function(array, fn) {
216+
if (typeof array.map == "function") {
217+
return array.map(fn)
218+
} else {
219+
var r = [];
220+
var l = array.length;
221+
for(i=0;i<l;i++) {
222+
r.push(fn(array[i]));
223+
}
224+
return r;
225+
}
209226
}
210227
};
211228

0 commit comments

Comments
 (0)