1
|
|
|
import bleach |
2
|
|
|
|
3
|
|
|
from django.utils.safestring import mark_safe |
4
|
|
|
|
5
|
|
|
from markdown import markdown |
6
|
|
|
|
7
|
|
|
from simple_forums.utils import get_setting |
8
|
|
|
|
9
|
|
|
|
10
|
|
|
class BaseRenderer: |
11
|
|
|
""" Base class that all renderers are based on """ |
12
|
|
|
|
13
|
|
|
def render(self, text): |
14
|
|
|
""" Render marked up text as html """ |
15
|
|
|
raise NotImplementedError |
16
|
|
|
|
17
|
|
|
|
18
|
|
|
class MarkdownRenderer(BaseRenderer): |
19
|
|
|
""" Handles rendering markdown into html """ |
20
|
|
|
|
21
|
|
|
DEFAULT_EXTENSIONS = [ |
22
|
|
|
'pymdownx.github', |
23
|
|
|
] |
24
|
|
|
|
25
|
|
|
# Attributes and tags used for rendering markdown taken from: |
26
|
|
|
# https://github.com/yourcelf/bleach-whitelist |
27
|
|
|
# |
28
|
|
|
# Slightly modified |
29
|
|
|
|
30
|
|
|
MARKDOWN_ATTRS = { |
31
|
|
|
'a': ['alt', 'href', 'title'], |
32
|
|
|
'img': ['alt', 'src', 'title'], |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
MARKDOWN_TAGS = { |
36
|
|
|
'a', |
37
|
|
|
'b', 'blockquote', 'br', |
38
|
|
|
'code', |
39
|
|
|
'dd', 'div', 'dt', |
40
|
|
|
'em', |
41
|
|
|
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', |
42
|
|
|
'i', 'img', |
43
|
|
|
'li', |
44
|
|
|
'ol', |
45
|
|
|
'p', |
46
|
|
|
'span', 'strong', |
47
|
|
|
'tt', |
48
|
|
|
'ul', |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
@staticmethod |
52
|
|
|
def get_extensions(): |
53
|
|
|
""" Get a list of extensions to use """ |
54
|
|
|
return get_setting( |
55
|
|
|
'markdown_extensions', |
56
|
|
|
MarkdownRenderer.DEFAULT_EXTENSIONS) |
57
|
|
|
|
58
|
|
|
def render(self, text): |
59
|
|
|
""" Convert the given text into html """ |
60
|
|
|
converted = markdown( |
61
|
|
|
text, |
62
|
|
|
extensions=MarkdownRenderer.get_extensions(), |
63
|
|
|
output_format='html5') |
64
|
|
|
|
65
|
|
|
cleaned = bleach.clean( |
66
|
|
|
converted, |
67
|
|
|
attributes=self.MARKDOWN_ATTRS, |
68
|
|
|
tags=self.MARKDOWN_TAGS) |
69
|
|
|
|
70
|
|
|
return mark_safe(cleaned) |
71
|
|
|
|
72
|
|
|
|
73
|
|
|
class TextRenderer(BaseRenderer): |
74
|
|
|
""" Renders text as itself """ |
75
|
|
|
|
76
|
|
|
def render(self, text): |
77
|
|
|
""" Return the text """ |
78
|
|
|
return text |
79
|
|
|
|