Skip to content

Commit 93a1b6b

Browse files
Add support for arrow functions to map filter.
1 parent 5915fe9 commit 93a1b6b

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/twig.filters.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -846,6 +846,25 @@ module.exports = function (Twig) {
846846
return template.render(data) === 'true';
847847
});
848848
}
849+
},
850+
map(value, params) {
851+
if (is('Array', value)) {
852+
const callBackParams = params.params.split(',');
853+
// Since Javascript does not support a callBack function to map() with both keys and values; we use forEach here
854+
// Note: Twig and PHP use ((value[, key])) for map(); whereas Javascript uses (([key, ]value)) for forEach()
855+
const newValue = [];
856+
value.forEach((_b, _a) => {
857+
const data = {};
858+
data[callBackParams[0]] = _b;
859+
if (callBackParams[1]) {
860+
data[callBackParams[1]] = _a;
861+
}
862+
863+
const template = Twig.exports.twig({data: params.body});
864+
newValue[_a] = template.render(data);
865+
});
866+
return newValue;
867+
}
849868
}
850869
};
851870

test/test.filters.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -871,6 +871,13 @@ describe('Twig.js Filters ->', function () {
871871
});
872872
});
873873

874+
describe('map ->', function () {
875+
it('should map an array (with keys)', function () {
876+
let testTemplate = twig({data: '{{ [1,5,2,7,8]|map((v) => v*v) }}'});
877+
testTemplate.render().should.equal('1,25,4,49,64');
878+
});
879+
});
880+
874881
it('should chain', function () {
875882
const testTemplate = twig({data: '{{ ["a", "b", "c"]|keys|reverse }}'});
876883
testTemplate.render().should.equal('2,1,0');

0 commit comments

Comments
 (0)