diff --git a/apps/templates/__init__.py b/apps/templates/__init__.py index bbd22c2034..32718411f9 100644 --- a/apps/templates/__init__.py +++ b/apps/templates/__init__.py @@ -16,7 +16,7 @@ from .content_templates import ContentTemplatesApplyResource, ContentTemplatesApplyService from .content_templates import create_scheduled_content # noqa from .content_templates import create_template_for_profile -from .filters import format_datetime_filter, first_paragraph_filter, iso_datetime +from .filters import format_datetime_filter, first_paragraph_filter, iso_datetime, add_timedelta from flask_babel import lazy_gettext @@ -42,5 +42,6 @@ def init_app(app) -> None: register_jinja_filter("first_paragraph", first_paragraph_filter) register_jinja_filter("get_text", get_text) register_jinja_filter("iso_datetime", iso_datetime) + register_jinja_filter("add_timedelta", add_timedelta) app.on_inserted_content_types += create_template_for_profile diff --git a/apps/templates/filters.py b/apps/templates/filters.py index 3a43401054..35ac7c9817 100644 --- a/apps/templates/filters.py +++ b/apps/templates/filters.py @@ -13,6 +13,7 @@ from superdesk import config from superdesk.etree import parse_html from lxml import etree +from datetime import timedelta logger = logging.getLogger(__name__) @@ -62,6 +63,13 @@ def first_paragraph_filter(input_string): return "" +def add_timedelta(date, **kwargs): + try: + return date + timedelta(**kwargs) + except Exception: + logger.warning("Failed to add minutes in Datetime - {}".format(date)) + + def iso_datetime(date): try: return date.isoformat() diff --git a/tests/templates/filters_test.py b/tests/templates/filters_test.py index 44bb1bb66b..d24600b7e6 100644 --- a/tests/templates/filters_test.py +++ b/tests/templates/filters_test.py @@ -9,8 +9,8 @@ # at https://www.sourcefabric.org/superdesk/license from flask import render_template_string - from superdesk.tests import TestCase +import datetime class ConvertDatetimeFiltersTest(TestCase): @@ -79,3 +79,15 @@ def test_get_first_paragraph_doesnt_fail_with_empty_body(self): item = {"headline": "Sample headline"} result = render_template_string(template_string, item=item) self.assertEqual(result, "") + + def test_add_timedelta(self): + template_string = "{{ item.datetime | add_timedelta(minutes=45)}}" + item = {"datetime": datetime.datetime(2021, 1, 1, 22, 54, 53)} + result = render_template_string(template_string, item=item) + self.assertEqual(result, "2021-01-01 23:39:53") + + def test_iso_datetime(self): + template_string = "{{ item.datetime | iso_datetime()}}" + item = {"datetime": datetime.datetime(2021, 1, 1, 22, 54, 53)} + result = render_template_string(template_string, item=item) + self.assertEqual(result, "2021-01-01T22:54:53")