本篇实现的作用是利用Jinja2模板根据需要生成html 页面。
ghtml.py内容如下:
# cat ghtml.py #!/usr/bin/env python # coding=utf-8 # code from www.361way.com import os from jinja2 import Environment, FileSystemLoader PATH = os.path.dirname(os.path.abspath(__file__)) TEMPLATE_ENVIRONMENT = Environment( autoescape=False, loader=FileSystemLoader(os.path.join(PATH, 'templates')), trim_blocks=False) def render_template(template_filename, context): return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context) def create_index_html(): fname = "output.html" urls = ['http://www.361way.com/tag/python', 'http://www.361way.com/tag/linux', 'http://www.361way.com/tag/mysql'] context = { 'urls': urls } # with open(fname, 'w') as f: html = render_template('index.html', context) f.write(html) def main(): create_index_html() ######################################## if __name__ == "__main__": main()
templates/index.html模板内容如下:
# cat templates/index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>generating html</title> </head> <body> <center> <h1>generating html</h1> <p>{{ urls|length }} links</p> </center> <ol align="left"> {% for url in urls -%} <li><a href="{{ url }}">{{ url }}</a></li> {% endfor -%} </ol> </body> </html>
执行后生成的内容如下:
# cat output.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>generating html</title> </head> <body> <center> <h1>generating html</h1> <p>3 links</p> </center> <ol align="left"> <li><a href="http://www.361way.com/tag/python">http://www.361way.com/tag/python</a></li> <li><a href="http://www.361way.com/tag/linux">http://www.361way.com/tag/linux</a></li> <li><a href="http://www.361way.com/tag/mysql">http://www.361way.com/tag/mysql</a></li> </ol> </body> </html>