diff --git a/src/Tags/EachTag.js b/src/Tags/EachTag.js index 42d5b52..a431bd7 100644 --- a/src/Tags/EachTag.js +++ b/src/Tags/EachTag.js @@ -260,10 +260,13 @@ class EachTag extends BaseTag { let index = 0 const total = _.size(data) _.each(data, (item, key) => { + const isEven = (index + 1) % 2 === 0 callback(item, { key: key, index: index, first: index === 0, + isOdd: !isEven, + isEven: isEven, last: (index + 1 === total), total: total }) diff --git a/test/unit/tags/each.spec.js b/test/unit/tags/each.spec.js index ea80fc7..15f502f 100644 --- a/test/unit/tags/each.spec.js +++ b/test/unit/tags/each.spec.js @@ -390,4 +390,22 @@ test.group('Tags | Each ', (group) => { const template = () => templateInstance.compileString(statement) assert.throw(template, `lineno:1 charno:1 E_INVALID_EXPRESSION: Invalid expression passed to (each) block`) }) + + test('set odd and even on $loop variable', (assert) => { + const statement = dedent` + @each(user in users) + {{ $loop.isOdd }} {{ $loop.isEven }} {{ ($loop.index + 1) }} + @endeach + ` + const template = new Template(this.tags).compileString(statement) + this.tags.each.run(Context) + + const ctx = new Context('', { + users: [{username: 'virk'}, {username: 'nikk'}] + }) + const output = new TemplateRunner(template, { + context: ctx + }).run() + assert.equal(output.trim(), 'true false 1\n false true 2') + }) })