fix #67: forloop.last, forloop.rindex, forloop.rindex0 incorrect if loop has a limit

This commit is contained in:
Jun Yang
2018-05-12 22:05:16 +08:00
parent 8e9e10fdb4
commit ef85bd9192
2 changed files with 43 additions and 6 deletions
+4 -5
View File
@@ -50,7 +50,6 @@ module.exports = function (liquid) {
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
var length = collection.length
var offset = hash.offset || 0
var limit = (hash.limit === undefined) ? collection.length : hash.limit
@@ -64,10 +63,10 @@ module.exports = function (liquid) {
first: i === 0,
index: i + 1,
index0: i,
last: i === length - 1,
length: length,
rindex: length - i,
rindex0: length - i - 1
last: i === collection.length - 1,
length: collection.length,
rindex: collection.length - i,
rindex0: collection.length - i - 1
}
return ctx
})
+39 -1
View File
@@ -135,11 +135,49 @@ describe('tags/for', function () {
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12')
})
it('should support for with limit and offset', function () {
it('should set forloop.last properly', function () {
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.last}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('false true ')
})
it('should set forloop.first properly', function () {
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.first}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('true false ')
})
it('should set forloop.length properly', function () {
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.length}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2 2 ')
})
})
describe('offset', function () {
it('should support offset with limit', function () {
var src = '{% for i in (1..10) limit:2 offset:5%}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('67')
})
it('should set index properly', function () {
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('1 2 ')
})
it('should set index0 properly', function () {
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index0}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('0 1 ')
})
it('should set rindex properly', function () {
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2 1 ')
})
it('should set rindex0 properly', function () {
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex0}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('1 0 ')
})
})
describe('reverse', function () {