Skip to content

Commit

Permalink
Cast arrays to boolean values unless checking their contents
Browse files Browse the repository at this point in the history
  • Loading branch information
dave-irvine committed Apr 17, 2016
1 parent 797ecbd commit 6654458
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/twig.expression.operator.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,16 @@ module.exports = function (Twig) {
b = stack.pop();
a = stack.pop();

if (operator !== 'in' && operator !== 'not in') {
if (a && Array.isArray(a)) {
a = a.length;
}

if (b && Array.isArray(b)) {
b = b.length;
}
}

switch (operator) {
case ':':
// Ignore
Expand Down
11 changes: 11 additions & 0 deletions test/test.expressions.js
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,17 @@ describe("Twig.js Expressions ->", function() {
test_template.render({a:false}).should.equal(true.toString());
test_template.render({a:true}).should.equal(false.toString());
});

it("should correctly cast arrays", function () {
var test_template = twig({data: '{{ a == true }}'});
test_template.render({a:['value']}).should.equal('true');
test_template.render({a:[]}).should.equal('false');
});

it("should correctly cast arrays in control structures", function () {
var test_template = twig({data: '{% if a is defined and a %}true{% else %}false{% endif %}'});
test_template.render({a:['value']}).should.equal('true');
});
});

describe("Other Operators ->", function() {
Expand Down

0 comments on commit 6654458

Please sign in to comment.