Skip to content

Commit

Permalink
Add base and default args to int filter
Browse files Browse the repository at this point in the history
  • Loading branch information
ogonkov authored and fdintino committed Jul 30, 2020
1 parent 0c02062 commit 7ef121c
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 6 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ Unreleased
* Add support for nested attributes on
[`sort` filter](https://mozilla.github.io/nunjucks/templating.html#sort-arr-reverse-casesens-attr);
respect `throwOnUndefined` if sort attribute is undefined.
* Add `base` arg to
[`int` filter](https://mozilla.github.io/nunjucks/templating.html#int).

3.2.2 (Jul 20 2020)
-------------------
Expand Down
4 changes: 3 additions & 1 deletion docs/templating.md
Original file line number Diff line number Diff line change
Expand Up @@ -1276,7 +1276,9 @@ Change default indentation to 6 spaces and indent the first line:
### int

Convert the value into an integer.
If the conversion fails 0 is returned.
If the conversion fails 0 is returned. You can override this default using the
first parameter. You can also override the default base (10) in the second
parameter.

**Input**

Expand Down
14 changes: 9 additions & 5 deletions nunjucks/src/filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -632,12 +632,16 @@ function float(val, def) {

exports.float = float;

function int(val, def) {
var res = parseInt(val, 10);
return (isNaN(res)) ? def : res;
}
const intFilter = r.makeMacro(
['value', 'default', 'base'],
[],
function doInt(value, defaultValue, base = 10) {
var res = parseInt(value, base);
return (isNaN(res)) ? defaultValue : res;
}
);

exports.int = int;
exports.int = intFilter;

// Aliases
exports.d = exports.default;
Expand Down
3 changes: 3 additions & 0 deletions tests/filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,9 @@
it('int', function() {
equal('{{ "3.5" | int }}', '3');
equal('{{ "0" | int }}', '0');
equal('{{ "foobar" | int("42") }}', '42');
equal('{{ "0x4d32" | int(base=16) }}', '19762');
equal('{{ "011" | int(base=8) }}', '9');
});

it('int (default value)', function() {
Expand Down

0 comments on commit 7ef121c

Please sign in to comment.