Fix commonmark template filter to turn urls and emails into clickables.
This commit is contained in:
parent
3a84dd62d2
commit
87a1361172
|
@ -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)
|
||||
|
|
Loading…
Reference in a new issue