Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array comparisons #883

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Fix casting of arrays.
  • Loading branch information
antoineveldhoven committed Nov 13, 2023
commit 7ab4254d8665908ad0a5ab79917535fb28f86582
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