Skip to content

Commit

Permalink
support .hasnext when iterating objects
Browse files Browse the repository at this point in the history
  • Loading branch information
rschick committed Apr 7, 2017
1 parent 198c9b6 commit f149fbf
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 21 deletions.
55 changes: 34 additions & 21 deletions src/compile/blocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,29 +195,42 @@ module.exports = function(Velocity, utils) {
return '';
}

var len = utils.isArray(_from) ? _from.length : utils.keys(_from).length;

utils.forEach(_from, function(val, i) {
if (utils.isArray(_from)) {
var len = _from.length;
utils.forEach(_from, function(val, i) {
if (this._state.break) {
return;
}
// 构造临时变量
local[_to] = val;
local.foreach = {
count: i + 1,
index: i,
hasNext: i + 1 < len
};
local.velocityCount = i + 1;

if (this._state.break) {
return;
}
// 构造临时变量
local[_to] = val;
// TODO: here, the foreach variable give to local, when _from is not an
// array, count and hasNext would be undefined, also i is not the
// index.
local.foreach = {
count: i + 1,
index: i,
hasNext: i + 1 < len
};
local.velocityCount = i + 1;

this.local[contextId] = local;
ret += this._render(_block, contextId);
this.local[contextId] = local;
ret += this._render(_block, contextId);

}, this);
}, this);
} else {
var len = utils.keys(_from).length;
utils.forEach(utils.keys(_from), function(key, i) {
if (this._state.break) {
return;
}
local[_to] = _from[key];
local.foreach = {
count: i + 1,
index: i,
hasNext: i + 1 < len
};
local.velocityCount = i + 1;
this.local[contextId] = local;
ret += this._render(_block, contextId);
}, this);
}

// if foreach items be an empty array, then this code will shift current
// conditions, but not this._render call, so this will shift parent context
Expand Down
6 changes: 6 additions & 0 deletions tests/foreach.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ describe('Loops', function() {
assert.equal(' name => hanwen ', render(vm, data))
})

it('#foreach with map hasNext', function() {
var vm = '#foreach($product in $products)$product.name#if($foreach.hasNext),#end#end'
var data = {products: {product1: {name: "hanwen1"}, product2: {name: "hanwen2"}, product3: {name: "hanwen3"}}};
assert.equal('hanwen1,hanwen2,hanwen3', render(vm, data))
})

it('#foreach with map keySet', function() {
var vm = '#foreach($key in $products.keySet())' +
' $key => $products.get($key) #end'
Expand Down

0 comments on commit f149fbf

Please sign in to comment.