bornhack-website/src/utils/templatetags/commonmark.py

34 lines
1 KiB
Python
Raw Normal View History

import bleach
import commonmark
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
register = template.Library()
def parse_commonmark(value):
parser = commonmark.Parser()
renderer = commonmark.HtmlRenderer()
ast = parser.parse(value)
2019-03-17 14:09:32 +00:00
return renderer.render(ast)
@register.filter(is_safe=True)
@stringfilter
def trustedcommonmark(value):
2019-01-22 07:57:24 +00:00
"""Returns HTML given some commonmark Markdown. Also allows real HTML, so do not use this with untrusted input."""
markdown = parse_commonmark(value)
result = bleach.linkify(markdown, parse_email=True)
2019-03-17 14:09:32 +00:00
return mark_safe(result)
@register.filter(is_safe=True)
@stringfilter
def untrustedcommonmark(value):
2019-01-22 07:57:24 +00:00
"""Returns HTML given some commonmark Markdown. Cleans actual HTML from input using bleach, suitable for use with untrusted input."""
2019-03-17 14:09:32 +00:00
cleaned = bleach.clean(value)
markdown = parse_commonmark(cleaned)
result = bleach.linkify(markdown, parse_email=True)
return mark_safe(result)