-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrender.py
60 lines (43 loc) · 1.61 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
import os
import shutil
import json
from jinja2 import Environment, FileSystemLoader, select_autoescape
global env, blog, OUT_PATH
OUT_PATH = "out"
if os.path.exists(OUT_PATH):
for child in os.listdir(OUT_PATH):
child = os.path.join(OUT_PATH, child)
if os.path.isfile(child):
os.remove(child)
else:
shutil.rmtree(child)
else:
os.mkdir(OUT_PATH)
os.mkdir(os.path.join(OUT_PATH, "blog"))
shutil.copy("robots.txt", OUT_PATH)
shutil.copy("favicon.png", OUT_PATH)
shutil.copy("style.css", OUT_PATH)
env = Environment(
loader=FileSystemLoader("templates"),
autoescape=select_autoescape()
)
def render(path, ctx = {}):
out_path = os.path.join(OUT_PATH, path).rsplit(".", 1)[0]
env.get_template(path).stream(ctx).dump(out_path)
with open("blog/index.json", "rt") as fp:
blog = json.load(fp)
def render_article(id, index = False):
article = blog["articles"][id]
with open(os.path.join("blog", id + ".txt"), "rt") as fp:
contents = fp.read()
paragraphs = contents.strip().split("\n\n")
fmt_articles = [{"id": id, **article} for id, article in blog["articles"].items()]
ctx = {"id": id, **article, "paragraphs": paragraphs, "articles": fmt_articles}
out_path = os.path.join(OUT_PATH, "blog", "index.html" if index else id + ".html")
env.get_template("article.html.j2").stream(ctx).dump(out_path)
render("index.html.j2")
render_article(blog["default"], True)
for id in blog["articles"].keys():
render_article(id)
out_path = os.path.join(OUT_PATH, "sitemap.xml")
env.get_template("sitemap.xml.j2").stream(blog).dump(out_path)