Home

Lin Lifeng's Blog

使用 python + markdown + github 搭建个人博客

我只需要一个很简单的功能,就是写好markdown文件,然后生成html放到Github Page上面就是了。这里只要用到下面几点的东西:

python代码:

import jinja2
import markdown
import codecs
from jinja2 import Template, Environment, FileSystemLoader
import os
import sys

if len(sys.argv) == 1:
    print 'require a file!!!'
    exit()

input_file = codecs.open(sys.argv[1], mode="r", encoding="utf-8-sig")
text = input_file.read()

extensions = [
    'extra',
    'meta',
    'nl2br',
    'sane_lists',
    'fenced_code',
    'codehilite(guess_lang=False, css_class=highlight)'
]
md = markdown.Markdown(extensions)
html = md.convert(text)
slug = md.Meta["slug"][0].strip().replace(' ', '-')
date = md.Meta["date"][0]

env = Environment(loader=FileSystemLoader("template"))
template = env.get_template("index.html")
result = template.render(content=html, meta=md.Meta, url_path=date+"/"+slug)

root = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(root, "output", date, slug)
if not os.path.exists(path):
    os.makedirs(path)
f = file(path + "/index.html", 'w')
f.write(result)
f.close()

github地址: https://github.com/linlifengx/md2page

comments powered by Disqus