Skip to content

Commit

Permalink
Add select filter
Browse files Browse the repository at this point in the history
  • Loading branch information
ogonkov authored and fdintino committed Apr 2, 2020
1 parent ec8eae5 commit 2031bf2
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
Changelog
=========

* Add [`select` filter](https://mozilla.github.io/nunjucks/templating.html#select).

3.2.1 (Mar 17 2020)
-------------------
* Replace yargs with commander to reduce number of dependencies. Merge of
Expand Down
27 changes: 27 additions & 0 deletions docs/templating.md
Original file line number Diff line number Diff line change
Expand Up @@ -1572,6 +1572,33 @@ escaping enabled this variable will not be escaped.
foo <a href="http://www.example.com/">http://www.example.com/</a> bar
```

### select

Filters a sequence of objects by applying a test to each object, and only
selecting the objects with the test succeeding.

If no test is specified, each object will be evaluated as a boolean.

**Input**

```jinja
{% set numbers=[0, 1, 2, 3, 4, 5] %}
{{ numbers | select("odd") | join }}
{{ numbers | select("even") | join }}
{{ numbers | select("divisibleby", 3) | join }}
{{ numbers | select() | join }}
```

**Output**

```jinja
135
024
03
12345
```

### selectattr (only the single-argument form)

Filter a sequence of objects by applying a test to the specified attribute
Expand Down
11 changes: 11 additions & 0 deletions nunjucks/src/filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,17 @@ function rejectattr(arr, attr) {

exports.rejectattr = rejectattr;

function select(arr, testName = 'truthy', secondArg) {
const context = this;
const test = context.env.getTest(testName);

return arr.filter(function applyToTest(item) {
return test.call(context, item, secondArg);
});
}

exports.select = select;

function selectattr(arr, attr) {
return arr.filter((item) => !!item[attr]);
}
Expand Down
16 changes: 16 additions & 0 deletions tests/filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,22 @@
finish(done);
});

it('select', function(done) {
var context = {
numbers: [0, 1, 2, 3, 4, 5]
};

equal('{{ numbers | select("odd") | join }}', context, '135');

equal('{{ numbers | select("even") | join }}', context, '024');

equal('{{ numbers | select("divisibleby", 3) | join }}', context, '03');

equal('{{ numbers | select() | join }}', context, '12345');

finish(done);
});

it('selectattr', function(done) {
var foods = [{
tasty: true
Expand Down

0 comments on commit 2031bf2

Please sign in to comment.