Skip to content
Myr

Added better partial() object collection support

Before adoption: this commit came in with the history the project adopted, so no landing records it.

only respecting .length is fine in some cases, but if the object has a length and has holes, it will likely produce an unexpected result, or an undefined local in the render call, which may some times be ideal, but most likely not. this change allows arbitrary objects to be passed to "collection: ", however unfortunately there is no way to arbitrarily assume the object is a collection without passing it as the option

authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent 885fb1f · Browse files · 3 files+45 added−8 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+45 added−8 removed

  • tests:+14 added−0 removed
  • other:+31 added−8 removed

3 files+45 added−8 removed

modified:lib/view.js+31 added-8 removed
111 unmodified lines
112113 // Collection support114 if (collection) {115 var len = collection.length116 , buf = '';116 , buf = ''117 , keys118 , key119 , val;120121 options.collectionLength = len;122123 if ('number' == typeof len || Array.isArray(collection)) {118 for (var i = 0; i < len; ++i) {119 var val = collection[i];120 options.firstInCollection = i === 0;121 options.indexInCollection = i;122 options.lastInCollection = i === len - 1;123 object = val;124 buf += render();124 for (var i = 0; i < len; ++i) {125 val = collection[i];126 options.firstInCollection = i == 0;127 options.indexInCollection = i;128 options.lastInCollection = i == len - 1;129 object = val;130 buf += render();131 } 132 } else {133 keys = Object.keys(collection);134 len = keys.length;135 options.collectionLength = len;136 options.collectionKeys = keys;137 for (var i = 0; i < len; ++i) {138 key = keys[i];139 val = collection[key];140 options.firstInCollection = i == 0;141 options.indexInCollection = i;142 options.keyInCollection = key;143 options.lastInCollection = i == len - 1;144 object = val;145 buf += render();146 }147 }148149 return buf;150 } else {151 return render();152 }
263 unmodified lines
added:test/fixtures/object-item.jade+1 added
1li #{keyInCollection}: #{item}
modified:test/view.test.js+13 added
369 unmodified lines
370 assert.equal(3, calls);371 });372 },373 374 'test #partial() collection object': function(){375 var app = create();376377 app.get('/', function(req, res){378 var items = { 2: 'foo', bar: 'bar' };379 res.partial('object-item.jade', { as: 'item', collection: items });380 });381382 assert.response(app,383 { url: '/' },384 { body: '<li>2: foo</li><li>bar: bar</li>' });385 },386 387 'test #partial()': function(){388 var app = create();389 390 app.set('view engine', 'jade');
692 unmodified lines