bornhack-website/src/utils/templatetags/commonmark.py
Thomas Steen Rasmussen 00af109e2f
add flake8 and isort to pre-commit config, make flake8 and isort happy (#441)
* add flake8 to pre-commit config, and fixup many things to make flake8 happy

* add isort and sort all imports, add to pre-commit and requirements
2020-02-12 13:10:41 +01:00

34 lines
1 KiB
Python

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)
return 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."""
markdown = parse_commonmark(value)
result = bleach.linkify(markdown, parse_email=True)
return mark_safe(result)
@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."""
cleaned = bleach.clean(value)
markdown = parse_commonmark(cleaned)
result = bleach.linkify(markdown, parse_email=True)
return mark_safe(result)