From 87a13611720cf465973a2010d6cdd154fe234ac9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=AD=C3=B0ir=20Valberg=20Gu=C3=B0mundsson?= Date: Sat, 9 Mar 2019 15:44:45 +0100 Subject: [PATCH] Fix commonmark template filter to turn urls and emails into clickables. --- src/utils/templatetags/commonmark.py | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/utils/templatetags/commonmark.py b/src/utils/templatetags/commonmark.py index 3de4f9ad..a01ce66e 100644 --- a/src/utils/templatetags/commonmark.py +++ b/src/utils/templatetags/commonmark.py @@ -1,5 +1,5 @@ -import commonmark, bleach -from html5lib.tokenizer import HTMLTokenizer +import commonmark +import bleach from django import template from django.utils.safestring import mark_safe @@ -7,23 +7,24 @@ from django.template.defaultfilters import stringfilter register = template.Library() +def parse_commonmark(value): + parser = commonmark.Parser() + renderer = commonmark.HtmlRenderer() + ast = parser.parse(value) + return mark_safe(renderer.render(ast)) + @register.filter(is_safe=True) @stringfilter def trustedcommonmark(value): """Returns HTML given some commonmark Markdown. Also allows real HTML, so do not use this with untrusted input.""" - parser = commonmark.Parser() - renderer = commonmark.HtmlRenderer() - ast = parser.parse(value) - return bleach.linkify(renderer.render(ast), skip_pre=True, parse_email=True, tokenizer=HTMLTokenizer) + linkified_value = bleach.linkify(value, parse_email=True) + return parse_commonmark(linkified_value) @register.filter(is_safe=True) @stringfilter def untrustedcommonmark(value): """Returns HTML given some commonmark Markdown. Cleans actual HTML from input using bleach, suitable for use with untrusted input.""" - parser = commonmark.Parser() - renderer = commonmark.HtmlRenderer() - ast = parser.parse(bleach.clean(value)) - return bleach.linkify(renderer.render(ast), skip_pre=True, parse_email=True, tokenizer=HTMLTokenizer) - + linkified_value = bleach.linkify(bleach.clean(value), parse_email=True) + return parse_commonmark(linkified_value)