Code

Ticket #2910: 2910-3.diff

File 2910-3.diff, 2.2 KB (added by wayla, 7 years ago)

Address older versions of markdown and unicode support.

Line 
1--- django/contrib/markup/templatetags/markup.py Wed Nov 07 15:03:56 2007
2+++ django/contrib/markup/templatetags/markup.py Wed Nov 07 16:09:56 2007
3@@ -30,15 +30,46 @@
4     else:
5         return force_unicode(textile.textile(smart_str(value), encoding='utf-8', output='utf-8'))
6 
7-def markdown(value):
8+def markdown(value, arg=''):
9+    """
10+    Runs Markdown over a given value, optionally using various
11+    extensions python-markdown supports.
12+   
13+    Syntax::
14+   
15+        {{ value|markdown:"extension1_name,extension2_name..." }}
16+   
17+    To enable safe mode, which strips raw HTML and only returns HTML
18+    generated by actual Markdown syntax, pass "safe" as the first
19+    extension in the list.
20+   
21+    If the version of Markdown in use does not support extensions,
22+    they will be silently ignored.
23+   
24+    """
25     try:
26         import markdown
27     except ImportError:
28         if settings.DEBUG:
29-            raise template.TemplateSyntaxError, "Error in {% markdown %} filter: The Python markdown library isn't installed."
30-        return force_unicode(value)
31+            raise template.TemplateSyntaxError('Error in markdown filter: Markdown could not be imported.')
32+        else:
33+            # Try to salvage this; whatever we do, we shouldn't
34+               # return potentially unsafe HTML.
35+            from django.utils.html import escape, linebreaks
36+               return linebreaks(escape(value))
37     else:
38-        return force_unicode(markdown.markdown(smart_str(value)))
39+        # markdown.version was first added in 1.6b. The only version of markdown
40+        # to fully support extensions before 1.6b was the shortlived 1.6a.
41+        if hasattr(markdown, 'version'):
42+            extensions = [e for e in arg.split(",") if e]
43+            if len(extensions) > 0 and extensions[0] == "safe":
44+                extensions = extensions[1:]
45+                safe_mode = True
46+            else:
47+                safe_mode = False
48+            return force_unicode(markdown.markdown(smart_str(value), extensions, safe_mode=safe_mode))
49+        else:
50+            return force_unicode(markdown.markdown(smart_str(value)))
51 
52 def restructuredtext(value):
53     try: