-
Notifications
You must be signed in to change notification settings - Fork 6
/
jinja2_markdown.py
62 lines (49 loc) · 1.56 KB
/
jinja2_markdown.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# -*- coding: utf-8 -*-
"""
jinja2_markdown
~~~~~~~~~~~~~~~~~~~~~~~~~
A jinja2 extension that adds a `{% markdown %}` tag.
:copyright: (c) 2014 by Daniel Chatfield
"""
import markdown
from jinja2.nodes import CallBlock
from jinja2.ext import Extension
class MarkdownExtension(Extension):
tags = set(['markdown'])
def __init__(self, environment):
super(MarkdownExtension, self).__init__(environment)
environment.extend(
markdowner=markdown.Markdown(extensions=['extra'])
)
def parse(self, parser):
lineno = next(parser.stream).lineno
body = parser.parse_statements(
['name:endmarkdown'],
drop_needle=True
)
return CallBlock(
self.call_method('_markdown_support'),
[],
[],
body
).set_lineno(lineno)
def _markdown_support(self, caller):
block = caller()
block = self._strip_whitespace(block)
return self._render_markdown(block)
def _strip_whitespace(self, block):
lines = block.split('\n')
whitespace = ''
output = ''
if (len(lines) > 1):
for char in lines[1]:
if (char == ' ' or char == '\t'):
whitespace += char
else:
break
for line in lines:
output += line.replace(whitespace, '', 1) + '\r\n'
return output.strip()
def _render_markdown(self, block):
block = self.environment.markdowner.convert(block)
return block