Skip to content

Commit

Permalink
Add support for arrow functions to map filter.
Browse files Browse the repository at this point in the history
  • Loading branch information
antoineveldhoven committed Sep 27, 2023
1 parent 5915fe9 commit 7c375e6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/twig.filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,26 @@ module.exports = function (Twig) {
return template.render(data) === 'true';
});
}
},
map(value, params) {
if (is('Array', value)) {
console.log(value);
const callBackParams = params.params.split(',');
// Since Javascript does not support a callBack function to map() with both keys and values; we use forEach here
// Note: Twig and PHP use ((value[, key])) for map(); whereas Javascript uses (([key, ]value)) for forEach()
const newValue = [];
value.forEach((_b, _a) => {
const data = {};
data[callBackParams[0]] = _b;
if (callBackParams[1]) {
data[callBackParams[1]] = _a;
}

const template = Twig.exports.twig({data: params.body});
newValue[_a] = template.render(data);
});
return newValue;
}
}
};

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

describe('map ->', function () {
it('should map an array (with keys)', function () {
let testTemplate = twig({data: '{{ [1,5,2,7,8]|map((v) => v*v) }}'});
testTemplate.render().should.equal('1,25,4,49,64');
});
});

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 7c375e6

Please sign in to comment.