From 29d6470a1848b3dd9aceb583ca9865fb876cfb02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20P=C3=A9ters?= Date: Wed, 31 Oct 2018 12:06:20 +0100 Subject: [PATCH] misc: add a |decimal template tag (#27699) --- tests/test_templates.py | 15 +++++++++++++++ wcs/qommon/templatetags/qommon.py | 13 +++++++++++++ 2 files changed, 28 insertions(+) diff --git a/tests/test_templates.py b/tests/test_templates.py index 2dd043cf5..7c66000d1 100644 --- a/tests/test_templates.py +++ b/tests/test_templates.py @@ -4,6 +4,7 @@ import pytest from quixote import cleanup from qommon.template import Template, TemplateError +from wcs.conditions import Condition from utilities import create_temporary_pub, clean_temporary_pub @@ -141,3 +142,17 @@ def test_datetime_templatetags(): def test_variable_unicode_error_handling(): tmpl = Template('{{ form_var_éléphant }}') assert tmpl.render() == '' + +def test_decimal_templatetag(): + tmpl = Template('{{ plop|decimal }}') + assert tmpl.render({'plop': 'toto'}) == '' + assert tmpl.render({'plop': '3.14'}) == '3.14' + assert tmpl.render({'plop': '3,14'}) == '3.14' + assert tmpl.render({'plop': 3.14}) == '3.14' + assert tmpl.render({'plop': 12345.678}) == '12345.678' + assert tmpl.render({'plop': None}) == '' + + tmpl = Template('{% if plop|decimal > 2 %}hello{% endif %}') + assert tmpl.render({'plop': 3}) == 'hello' + assert tmpl.render({'plop': 1}) == '' + assert tmpl.render({'plop': None}) == 'hello' # will be str > int, always True. diff --git a/wcs/qommon/templatetags/qommon.py b/wcs/qommon/templatetags/qommon.py index 4b65fd938..9ad0de7b4 100644 --- a/wcs/qommon/templatetags/qommon.py +++ b/wcs/qommon/templatetags/qommon.py @@ -15,6 +15,7 @@ # along with this program; if not, see . import datetime +from decimal import Decimal from django import template from django.template import defaultfilters @@ -75,6 +76,18 @@ def date(value, arg=None): value = parse_date(value) return defaultfilters.date(value, arg=arg) +@register.filter(is_safe=True) +def decimal(value): + if not value: + return '' + try: + if isinstance(value, basestring): + # replace , by . for French users comfort + value = value.replace(',', '.') + return Decimal(value).quantize(Decimal('1.0000')).normalize() + except ArithmeticError: + return '' + @register.simple_tag def standard_text(text_id): return mark_safe(TextsDirectory.get_html_text(str(text_id))) -- 2.19.1