summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBen Timms <ben.timms@gmail.com>2015-04-29 16:45:46 +0100
committerBen Timms <ben.timms@gmail.com>2015-04-29 16:45:46 +0100
commit97a8aafb8d0d44951a9baac2f54a276c55c7e195 (patch)
treebdfce9da642ebf5b8ab1b72a3eeb2dbddabd046d
parentbd93bf35111d73eb00ef6597a1ec002170c1cd87 (diff)
downloadjinja2-97a8aafb8d0d44951a9baac2f54a276c55c7e195.tar.gz
Add 'base' parameter to 'int' filter
-rw-r--r--jinja2/filters.py9
-rw-r--r--tests/test_filters.py5
2 files changed, 9 insertions, 5 deletions
diff --git a/jinja2/filters.py b/jinja2/filters.py
index 0fb5a5a..cfe4594 100644
--- a/jinja2/filters.py
+++ b/jinja2/filters.py
@@ -510,13 +510,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:
diff --git a/tests/test_filters.py b/tests/test_filters.py
index 42c5558..741ef34 100644
--- a/tests/test_filters.py
+++ b/tests/test_filters.py
@@ -134,9 +134,10 @@ class TestFilter():
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("|") }}')