From a7a65c12c0d63600517296d4b779a89476a981a8 Mon Sep 17 00:00:00 2001 From: Maximilian Moser <maximilian.moser@tuwien.ac.at> Date: Mon, 17 Mar 2025 20:07:53 +0100 Subject: [PATCH] Allow email notifications to render a different template * by temporarily overriding the `notification.type` --- invenio_config_tuw/notifications/backends.py | 23 +++++++++++++++++++- invenio_config_tuw/notifications/builders.py | 6 ++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/invenio_config_tuw/notifications/backends.py b/invenio_config_tuw/notifications/backends.py index c4ad17c..dd7d937 100644 --- a/invenio_config_tuw/notifications/backends.py +++ b/invenio_config_tuw/notifications/backends.py @@ -7,6 +7,8 @@ """Custom notification backends for TU Wien.""" +from contextlib import contextmanager + from flask import current_app from invenio_mail.tasks import send_email from invenio_notifications.backends.email import EmailNotificationBackend @@ -15,6 +17,24 @@ from marshmallow_utils.html import strip_html from ..proxies import current_config_tuw +@contextmanager +def temp_hack_notification_type(notification): + """Temporarily override the ``notification.type``. + + This enables notifications built by our custom user/group notification builders + to render templates that are not ``{user,group}-notification.jinja``. + """ + old_notif_type = notification.type + temp_type = getattr( + notification, "template_name", notification.context.get("template_name", None) + ) + if temp_type: + notification.type = temp_type.rstrip(".jinja") + + yield notification + notification.type = old_notif_type + + class TUWEmailNotificationBackend(EmailNotificationBackend): """Email notification backend extended for the use cases at TU Wien. @@ -24,7 +44,8 @@ class TUWEmailNotificationBackend(EmailNotificationBackend): def send(self, notification, recipient): """Mail sending implementation.""" - content = self.render_template(notification, recipient) + with temp_hack_notification_type(notification): + content = self.render_template(notification, recipient) subject = content["subject"] # if a site identifier is configured, we set is as prefix for email subjects diff --git a/invenio_config_tuw/notifications/builders.py b/invenio_config_tuw/notifications/builders.py index 6eb0d61..e16fa5d 100644 --- a/invenio_config_tuw/notifications/builders.py +++ b/invenio_config_tuw/notifications/builders.py @@ -27,10 +27,12 @@ class UserNotificationBuilder(NotificationBuilder): cls, receiver, subject, - message, + message=None, html_message=None, plain_message=None, md_message=None, + template_name=None, + **kwargs, ): """Build notification with context.""" return Notification( @@ -42,6 +44,8 @@ class UserNotificationBuilder(NotificationBuilder): "html_message": html_message, "plain_message": plain_message, "md_message": md_message, + "template_name": template_name, + **kwargs, }, ) -- GitLab