From 0b83ad6b3e53a80943a12c92015478f76ba49e3a Mon Sep 17 00:00:00 2001 From: Herculino Trotta Date: Wed, 29 Jan 2025 13:52:46 -0300 Subject: [PATCH] feat: allow for a subset of markdown (bold, italics, strikethrough, links) when displaying notes --- app/apps/common/templatetags/markdown.py | 52 ++++++++++++++++++++++ app/templates/cotton/transaction/item.html | 3 +- requirements.txt | 1 + 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 app/apps/common/templatetags/markdown.py diff --git a/app/apps/common/templatetags/markdown.py b/app/apps/common/templatetags/markdown.py new file mode 100644 index 0000000..547aaad --- /dev/null +++ b/app/apps/common/templatetags/markdown.py @@ -0,0 +1,52 @@ +from typing import Optional + +import mistune +from django import template +from django.utils.safestring import mark_safe +from mistune import HTMLRenderer, Markdown, BlockParser, InlineParser, safe_entity +from mistune.plugins.formatting import strikethrough as plugin_strikethrough +from mistune.plugins.url import url as plugin_url + + +register = template.Library() + + +class CustomRenderer(HTMLRenderer): + def link(self, text: str, url: str, title: Optional[str] = None) -> str: + s = '" + text + "" + + def paragraph(self, text: str) -> str: + return text + "\n" + + def softbreak(self) -> str: + return "\n" + + def blank_line(self) -> str: + return "\n" + + +block = BlockParser() +block.rules = ["blank_line"] +inline = InlineParser(hard_wrap=False) +inline.rules = [ + "emphasis", + "link", + "auto_link", + "auto_email", + "linebreak", + "softbreak", +] +markdown = Markdown( + renderer=CustomRenderer(escape=False), + block=block, + inline=inline, + plugins=[plugin_strikethrough, plugin_url], +) + + +@register.filter(name="limited_markdown") +def limited_markdown(value): + return mark_safe(markdown(value)) diff --git a/app/templates/cotton/transaction/item.html b/app/templates/cotton/transaction/item.html index 02ba143..bdc86b4 100644 --- a/app/templates/cotton/transaction/item.html +++ b/app/templates/cotton/transaction/item.html @@ -1,3 +1,4 @@ +{% load markdown %} {% load i18n %}
{% if not disable_selection %} @@ -54,7 +55,7 @@ {% if transaction.notes %}
-
{{ transaction.notes | linebreaksbr }}
+
{{ transaction.notes | limited_markdown | linebreaksbr }}
{% endif %} {# Category#} diff --git a/requirements.txt b/requirements.txt index 1fc5d50..58c34db 100644 --- a/requirements.txt +++ b/requirements.txt @@ -26,3 +26,4 @@ python-dateutil~=2.9.0.post0 simpleeval~=1.0.0 pydantic~=2.10.5 PyYAML~=6.0.2 +mistune~=3.1.1