Skip to content

Commit

Permalink
feat(each-tag): add isEven and isOdd to
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Mar 28, 2017
1 parent 5c86bb0 commit 9be4fbe
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/Tags/EachTag.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
Expand Down
18 changes: 18 additions & 0 deletions test/unit/tags/each.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 <calories, name in veggies, { include: 'includes.veggie' }> 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')
})
})

0 comments on commit 9be4fbe

Please sign in to comment.