Skip to content

Commit

Permalink
Merge pull request #447 from bentimms/int-filter-base
Browse files Browse the repository at this point in the history
Add 'base' parameter to 'int' filter
  • Loading branch information
untitaker committed Jun 1, 2015
2 parents d2ffef5 + 97a8aaf commit 3bb8a1f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
9 changes: 6 additions & 3 deletions jinja2/filters.py
Expand Up @@ -511,13 +511,16 @@ def do_wordcount(s):
return len(_word_re.findall(s))


def do_int(value, default=0):
def do_int(value, default=0, base=10):
"""Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter.
override this default using the first parameter. You
can also override the default base (10) in the second
parameter, which handles input with prefixes such as
0b, 0o and 0x for bases 2, 8 and 16 respectively.
"""
try:
return int(value)
return int(value, base)
except (TypeError, ValueError):
# this quirk is necessary so that "42.23"|int gives 42.
try:
Expand Down
5 changes: 3 additions & 2 deletions tests/test_filters.py
Expand Up @@ -134,9 +134,10 @@ def test_indent(self, env):

def test_int(self, env):
tmpl = env.from_string('{{ "42"|int }}|{{ "ajsghasjgd"|int }}|'
'{{ "32.32"|int }}')
'{{ "32.32"|int }}|{{ "0x4d32"|int(0, 16) }}|'
'{{ "011"|int(0, 8)}}|{{ "0x33FU"|int(0, 16) }}')
out = tmpl.render()
assert out == '42|0|32'
assert out == '42|0|32|19762|9|0'

def test_join(self, env):
tmpl = env.from_string('{{ [1, 2, 3]|join("|") }}')
Expand Down

0 comments on commit 3bb8a1f

Please sign in to comment.