本篇实现的作用是利用Jinja2模板根据需要生成html 页面。

ghtml.py内容如下:

 1# cat ghtml.py
 2#!/usr/bin/env python
 3# coding=utf-8
 4# code from www.361way.com
 5import os
 6from jinja2 import Environment, FileSystemLoader
 7PATH = os.path.dirname(os.path.abspath(__file__))
 8TEMPLATE_ENVIRONMENT = Environment(
 9    autoescape=False,
10    loader=FileSystemLoader(os.path.join(PATH, 'templates')),
11    trim_blocks=False)
12def render_template(template_filename, context):
13    return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)
14def create_index_html():
15    fname = "output.html"
16    urls = ['http://www.361way.com/tag/python', 'http://www.361way.com/tag/linux', 'http://www.361way.com/tag/mysql']
17    context = {
18        'urls': urls
19    }
20    #
21    with open(fname, 'w') as f:
22        html = render_template('index.html', context)
23        f.write(html)
24def main():
25    create_index_html()
26########################################
27if __name__ == "__main__":
28    main()

templates/index.html模板内容如下:

 1# cat templates/index.html
 2<!DOCTYPE html>
 3<html>
 4<head>
 5    <meta charset="utf-8"/>
 6    <title>generating html</title>
 7</head>
 8<body>
 9<center>
10    <h1>generating html</h1>
11    <p>{{ urls|length }} links</p>
12</center>
13<ol align="left">
14{% for url in urls -%}
15<li><a href="{{ url }}">{{ url }}</a></li>
16{% endfor -%}
17</ol>
18</body>
19</html>

执行后生成的内容如下:

 1# cat output.html
 2<!DOCTYPE html>
 3<html>
 4<head>
 5    <meta charset="utf-8"/>
 6    <title>generating html</title>
 7</head>
 8<body>
 9<center>
10    <h1>generating html</h1>
11    <p>3 links</p>
12</center>
13<ol align="left">
14<li><a href="http://www.361way.com/tag/python">http://www.361way.com/tag/python</a></li>
15<li><a href="http://www.361way.com/tag/linux">http://www.361way.com/tag/linux</a></li>
16<li><a href="http://www.361way.com/tag/mysql">http://www.361way.com/tag/mysql</a></li>
17</ol>
18</body>
19</html>