2019-03-09 14:44:45 +00:00
|
|
|
import bleach
|
2020-02-12 12:10:41 +00:00
|
|
|
import commonmark
|
2016-05-30 19:51:17 +00:00
|
|
|
from django import template
|
2016-08-15 07:03:28 +00:00
|
|
|
from django.template.defaultfilters import stringfilter
|
2020-02-12 12:10:41 +00:00
|
|
|
from django.utils.safestring import mark_safe
|
2016-05-30 19:51:17 +00:00
|
|
|
|
|
|
|
register = template.Library()
|
|
|
|
|
2019-03-18 20:39:05 +00:00
|
|
|
|
2019-03-09 14:44:45 +00:00
|
|
|
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)
|
2019-03-09 14:44:45 +00:00
|
|
|
|
2016-05-30 19:51:17 +00:00
|
|
|
|
2019-02-17 16:39:42 +00:00
|
|
|
@register.filter(is_safe=True)
|
2016-08-15 07:03:28 +00:00
|
|
|
@stringfilter
|
2018-06-03 13:34:04 +00:00
|
|
|
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."""
|
2019-03-18 20:39:05 +00:00
|
|
|
markdown = parse_commonmark(value)
|
|
|
|
result = bleach.linkify(markdown, parse_email=True)
|
2019-03-17 14:09:32 +00:00
|
|
|
return mark_safe(result)
|
2016-08-15 07:22:48 +00:00
|
|
|
|
2019-02-17 16:39:42 +00:00
|
|
|
|
|
|
|
@register.filter(is_safe=True)
|
2016-08-15 07:22:48 +00:00
|
|
|
@stringfilter
|
2018-06-03 13:34:04 +00:00
|
|
|
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)
|