You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

stagen.py 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from jinja2 import Template, Environment, PackageLoader, select_autoescape, FileSystemLoader, PrefixLoader
  2. import os
  3. import errno
  4. import markdown
  5. import codecs
  6. import time
  7. env = Environment(
  8. loader=PrefixLoader({
  9. 'templates': FileSystemLoader('templates'),
  10. 'content': FileSystemLoader('content')
  11. })
  12. )
  13. def ensure_dir_exists(path):
  14. try:
  15. os.makedirs(path)
  16. except OSError as exception:
  17. if exception.errno != errno.EEXIST:
  18. raise
  19. def filter_templates(template):
  20. if template.startswith("content/") and template.endswith('.html'):
  21. return True
  22. return False
  23. content_template_names=env.list_templates(filter_func=filter_templates)
  24. for template_name in content_template_names:
  25. template = env.get_template(template_name)
  26. fname = template_name[len("content/"):] # trim off front of path
  27. fname = os.path.join("output", fname)
  28. ensure_dir_exists(os.path.dirname(fname))
  29. f = open(fname, 'w')
  30. f.write(template.render())
  31. ensure_dir_exists("posts")
  32. md = markdown.Markdown(extensions = ['markdown.extensions.meta'])
  33. post_files = os.listdir("posts")
  34. post_list = []
  35. for post_file in post_files:
  36. text = codecs.open(os.path.join("posts", post_file), mode="r", encoding="utf-8").read()
  37. html = md.convert(text)
  38. postinfo = dict()
  39. postinfo['url'] = os.path.join("/posts/" + md.Meta['slug'][0] + '.html')
  40. postinfo['date'] = time.strptime(md.Meta['date'][0], "%Y-%m-%d")
  41. postinfo['title'] = md.Meta['title'][0]
  42. post_list.append(postinfo)
  43. fname = os.path.join("output/posts", md.Meta['slug'][0] + '.html')
  44. ensure_dir_exists(os.path.dirname(fname))
  45. template = env.get_template("templates/post.html")
  46. page = template.render(html=html, meta=md.Meta)
  47. f = open(fname, 'w')
  48. f.write(page)
  49. #sort post list by date
  50. sorted_post_list = sorted(post_list, key=lambda k: k['date'], reverse=True)
  51. template = env.get_template("templates/posts.html")
  52. f = open("output/posts.html", 'w')
  53. f.write(template.render(posts=sorted_post_list))