利用Jinja2模板生成html页面
本篇实现的作用是利用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>
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/jinja2-generate-html/5359.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.