Skip to content

Commit

Permalink
Add support for arrow functions to filter filter.
Browse files Browse the repository at this point in the history
  • Loading branch information
antoineveldhoven committed Sep 26, 2023
1 parent f7c4666 commit 5915fe9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/twig.filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -835,6 +835,17 @@ module.exports = function (Twig) {
},
spaceless(value) {
return value.replace(/>\s+</g, '><').trim();
},
filter(value, params) {
if (is('Array', value)) {
return value.filter(_a => {
const data = {};
data[params.params] = _a;

const template = Twig.exports.twig({data: params.body});
return template.render(data) === 'true';
});
}
}
};

Expand Down
12 changes: 12 additions & 0 deletions test/test.filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -859,6 +859,18 @@ describe('Twig.js Filters ->', function () {
});
});

describe('filter ->', function () {
it('should filter an array (with perenthesis)', function () {
let testTemplate = twig({data: '{{ [1,5,2,7,8]|filter((f) => f % 2 == 0) }}'});
testTemplate.render().should.equal('2,8');
});

it('should filter an array (without perenthesis)', function () {
let testTemplate = twig({data: '{{ [1,5,2,7,8]|filter(f => f % 2 == 0) }}'});
testTemplate.render().should.equal('2,8');
});
});

it('should chain', function () {
const testTemplate = twig({data: '{{ ["a", "b", "c"]|keys|reverse }}'});
testTemplate.render().should.equal('2,1,0');
Expand Down

0 comments on commit 5915fe9

Please sign in to comment.