diff --git a/src/twig.filters.js b/src/twig.filters.js index b6f18f0a..f2a2a258 100644 --- a/src/twig.filters.js +++ b/src/twig.filters.js @@ -846,6 +846,25 @@ module.exports = function (Twig) { return template.render(data) === 'true'; }); } + }, + map(value, params) { + if (is('Array', 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; + } } }; diff --git a/test/test.filters.js b/test/test.filters.js index 1583982c..680fda42 100644 --- a/test/test.filters.js +++ b/test/test.filters.js @@ -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');