利用Jinja2模板生成html页面

本篇实现的作用是利用<a href="http://jinja.pocoo.org/docs/" target="_blank" rel="noopener">Jinja2</a>模板根据需要生成html 页面。



ghtml.py内容如下:



<br />
# 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 = ['https://www.361way.com/tag/python', 'https://www.361way.com/tag/linux', 'https://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模板内容如下:



<br />
# cat templates/index.html



    
    generating html


generating html

{{ urls|length }} links
    {% for url in urls -%}
  1. {{ url }}
  2. {% endfor -%}
执行后生成的内容如下:



<br />
# cat output.html



    
    generating html


generating html

3 links
  1. https://www.361way.com/tag/python
  2. https://www.361way.com/tag/linux
  3. https://www.361way.com/tag/mysql
<br />

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注