Skip to content

Commit

Permalink
Fix casting of arrays.
Browse files Browse the repository at this point in the history
  • Loading branch information
antoineveldhoven committed Nov 13, 2023
1 parent dca18b4 commit 7ab4254
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/twig.expression.operator.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,12 +178,13 @@ module.exports = function (Twig) {
}

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

if (operator !== '?' && (b && Array.isArray(b))) {
b = b.length;
if (operator !== '?' && a && Array.isArray(a) && typeof b === 'boolean') {
a = Twig.lib.boolval(a);
} else if (operator !== '?' && b && Array.isArray(b) && typeof a === 'boolean') {
b = Twig.lib.boolval(b);
} else if (operator === '==' && ((a && Array.isArray(a)) || (b && Array.isArray(b)))) {
a = JSON.stringify(a);
b = JSON.stringify(b);
}
}

Expand Down
6 changes: 6 additions & 0 deletions test/test.expressions.js
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,13 @@ describe('Twig.js Expressions ->', function () {
it('should correctly cast arrays', function () {
const testTemplate = twig({data: '{{ a == true }}'});
testTemplate.render({a: ['value']}).should.equal('true');
testTemplate.render({a: ['value', 'another']}).should.equal('true');
testTemplate.render({a: []}).should.equal('false');

const testTemplate2 = twig({data: '{{ true == a }}'});
testTemplate2.render({a: ['value']}).should.equal('true');
testTemplate2.render({a: ['value', 'another']}).should.equal('true');
testTemplate2.render({a: []}).should.equal('false');
});

it('should correctly cast arrays in control structures', function () {
Expand Down

0 comments on commit 7ab4254

Please sign in to comment.