use bleach.linkify to make links in markdown clickable automagically, fixes #64

This commit is contained in:
Thomas Steen Rasmussen 2019-02-17 17:39:42 +01:00
parent 8c9b2d11bf
commit 3a84dd62d2
3 changed files with 8 additions and 6 deletions

View file

@ -14,5 +14,5 @@
{% endif %}
<h3>{{ news_item.title }} <small>{{ news_item.published_at|date:"Y-m-d" }}</small></h3>
</div>
{{ news_item.content|trustedcommonmark }}
{{ news_item.content|trustedcommonmark|urlize }}
{% endblock %}

View file

@ -13,7 +13,7 @@ News | {{ block.super }}
<div>
<h3><a href="{% url 'news:detail' slug=item.slug %}">{{ item.title }}</a> <small>{{ item.published_at|date:"Y-m-d" }}</small></h3>
</div>
{{ item.content|trustedcommonmark }}
{{ item.content|trustedcommonmark|urlize }}
{% if not forloop.last %}
<hr />
{% endif %}

View file

@ -1,4 +1,5 @@
import commonmark, bleach
from html5lib.tokenizer import HTMLTokenizer
from django import template
from django.utils.safestring import mark_safe
@ -7,21 +8,22 @@ from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter
@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 mark_safe(renderer.render(ast))
return bleach.linkify(renderer.render(ast), skip_pre=True, parse_email=True, tokenizer=HTMLTokenizer)
@register.filter
@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 mark_safe(renderer.render(ast))
return bleach.linkify(renderer.render(ast), skip_pre=True, parse_email=True, tokenizer=HTMLTokenizer)