-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.py
99 lines (74 loc) · 2.68 KB
/
render.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import re
from pathlib import Path
from mako.lookup import TemplateLookup
import markdown2
from pyquery import PyQuery
from lxml import etree
from common import site_dir, template_dir, site_root
lookup = TemplateLookup(
directories=[str(template_dir)],
strict_undefined=True,
)
def render_template(template_file, **kwargs):
template_path = template_dir / template_file
kwargs.update(
ROOT=site_root,
PATH=template_path,
)
tmpl = lookup.get_template(str(template_file))
return tmpl.render(**kwargs)
def get_doc(md_file):
md_file = site_dir / md_file
return MarkdownDocument(md_file)
class MarkdownDocument:
def __init__(self, md_file):
self.title = None
# Use the first h1 as the title. All subsequent h1's are turned into
# h2's.
def gen():
for line in md_file.read_text().splitlines():
if re.match(r'^# ', line):
if self.title is None:
self.title = line[1:].strip()
yield line
else:
yield '#' + line # turn h1 into h2
else:
yield line
self.text = '\n'.join(gen())
@property
def html(self):
return markdown2.markdown(self.text)
def get_lesson_html(self):
doc = PyQuery(self.html)
for link in doc('a.external'):
link.set('target', '_blank')
for img in doc('img'):
img.set('class', 'img-responsive')
return doc_to_string(doc)
def get_slides_html(self):
html = self.html.replace('<hr />', '</section>\n<section>')
html = '<div class="slides">\n<section>\n{}\n</section>\n</div>'.format(html)
doc = PyQuery(html)
# All local images must have their src attributes reference files in the
# parent directory.
for img in doc('img'):
src = img.get('src')
if not src.startswith('http'):
img.set('src', '../' + src)
# All links in slideshow open a new tab.
for link in doc('a'):
link.set('target', '_blank')
# Make sure that images are scaled correctly inside slides. That can
# only happen if img elements are not children of p elements.
for img in doc('img'):
img.attrib['class'] = 'stretch'
parent = img.getparent()
if parent.tag == 'p':
parent.getparent().replace(parent, img)
return doc_to_string(doc)
def doc_to_string(doc):
"""
Serialize the given PyQuery object to an HTML string.
"""
return etree.tostring(doc[0], encoding='unicode', method='html')