diff --git a/src/twig.expression.operator.js b/src/twig.expression.operator.js index 027382e1..be84c914 100644 --- a/src/twig.expression.operator.js +++ b/src/twig.expression.operator.js @@ -17,6 +17,11 @@ module.exports = function (Twig) { return null; } + if (b && Array.isArray(b)) { + // Array + return JSON.stringify(b).includes(JSON.stringify(a)); + } + if (b.indexOf !== undefined) { // String return (a === b || a !== '') && b.includes(a); @@ -173,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); } } diff --git a/test/test.expressions.js b/test/test.expressions.js index 3563bd80..dc40fbc8 100644 --- a/test/test.expressions.js +++ b/test/test.expressions.js @@ -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 () { @@ -381,6 +387,12 @@ describe('Twig.js Expressions ->', function () { testTemplate = twig({data: '{{ "d" in ["a", "b", "c"] }}'}); testTemplate.render().should.equal(false.toString()); + + testTemplate = twig({data: '{{ ["a", "b"] in [["a", "b"], ["c", "d"]] }}'}); + testTemplate.render().should.equal(true.toString()); + + testTemplate = twig({data: '{{ ["a", "c"] in [["a", "b"], ["c", "d"]] }}'}); + testTemplate.render().should.equal(false.toString()); }); it('should support not in/containment functionality for arrays', function () { @@ -391,6 +403,12 @@ describe('Twig.js Expressions ->', function () { testTemplate = twig({data: '{{ "d" not in ["a", "b", "c"] }}'}); testTemplate.render().should.equal(true.toString()); + + testTemplate = twig({data: '{{ ["a", "b"] not in [["a", "b"], ["c", "d"]] }}'}); + testTemplate.render().should.equal(false.toString()); + + testTemplate = twig({data: '{{ ["a", "c"] not in [["a", "b"], ["c", "d"]] }}'}); + testTemplate.render().should.equal(true.toString()); }); it('should support in/containment functionality for strings', function () {