forked from Khan/react-components
-
Notifications
You must be signed in to change notification settings - Fork 0
/
make_template.py
executable file
·55 lines (40 loc) · 1.8 KB
/
make_template.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
#!/usr/bin/env python
import os.path
import jinja2
from jinja2.ext import Extension
class CodeExampleExtension(Extension):
"""Insert a code example.
My plan for the docs is side-by-side code and live widgets. I plan to make
this extension fancier in the future, since I would like one file to serve
as the source of both the pretty code we display to the user and the
widget. I have a vague idea of how that will work - I think there will have
to be a header/footer that will be inserted for any given example, then
this command will strip that out, put it where it needs to go, and format
the code nicely.
http://jinja.pocoo.org/docs/extensions/#adding-extensions
"""
tags = set(["code_example"])
def __init__(self, environment):
super(CodeExampleExtension, self).__init__(environment)
# {% code_example "filename" %}
# ^------------------ first token, call next() to advance past it
# ^----- generate self._insert("filename")
def parse(self, parser):
lineno = parser.stream.next().lineno
filename = parser.parse_expression()
return (jinja2.nodes
.CallBlock(self.call_method('_insert', [filename]), [], [], [])
.set_lineno(lineno))
def _insert(self, filename, caller):
path = os.path.join('examples', filename)
with open(path, 'r') as f:
example = f.read()
return (jinja2.Markup("<div class='example_div'>%s</div>") %
example.strip())
if __name__ == '__main__':
loader = jinja2.FileSystemLoader('.')
env = jinja2.Environment(loader=loader, extensions=[CodeExampleExtension])
template = env.get_template('template.html')
with open('docs/index.html', 'w') as f:
f.seek(0)
f.write(template.render())