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
|
import commonmark
|
||||||
from html5lib.tokenizer import HTMLTokenizer
|
import bleach
|
||||||
|
|
||||||
from django import template
|
from django import template
|
||||||
from django.utils.safestring import mark_safe
|
from django.utils.safestring import mark_safe
|
||||||
|
@ -7,23 +7,24 @@ from django.template.defaultfilters import stringfilter
|
||||||
|
|
||||||
register = template.Library()
|
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)
|
@register.filter(is_safe=True)
|
||||||
@stringfilter
|
@stringfilter
|
||||||
def trustedcommonmark(value):
|
def trustedcommonmark(value):
|
||||||
"""Returns HTML given some commonmark Markdown. Also allows real HTML, so do not use this with untrusted input."""
|
"""Returns HTML given some commonmark Markdown. Also allows real HTML, so do not use this with untrusted input."""
|
||||||
parser = commonmark.Parser()
|
linkified_value = bleach.linkify(value, parse_email=True)
|
||||||
renderer = commonmark.HtmlRenderer()
|
return parse_commonmark(linkified_value)
|
||||||
ast = parser.parse(value)
|
|
||||||
return bleach.linkify(renderer.render(ast), skip_pre=True, parse_email=True, tokenizer=HTMLTokenizer)
|
|
||||||
|
|
||||||
|
|
||||||
@register.filter(is_safe=True)
|
@register.filter(is_safe=True)
|
||||||
@stringfilter
|
@stringfilter
|
||||||
def untrustedcommonmark(value):
|
def untrustedcommonmark(value):
|
||||||
"""Returns HTML given some commonmark Markdown. Cleans actual HTML from input using bleach, suitable for use with untrusted input."""
|
"""Returns HTML given some commonmark Markdown. Cleans actual HTML from input using bleach, suitable for use with untrusted input."""
|
||||||
parser = commonmark.Parser()
|
linkified_value = bleach.linkify(bleach.clean(value), parse_email=True)
|
||||||
renderer = commonmark.HtmlRenderer()
|
return parse_commonmark(linkified_value)
|
||||||
ast = parser.parse(bleach.clean(value))
|
|
||||||
return bleach.linkify(renderer.render(ast), skip_pre=True, parse_email=True, tokenizer=HTMLTokenizer)
|
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue