Jinja2模块生成html

1、html模板,文件名为:template.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>Title</title>
</head>
<h1>巡检报告</h1>
<body>
<h2>报告综述</h2>
<p>巡检地点 : 机房  开始时间 : {{ start_time }}  结束时间 : {{ stop_time }}  </p>
<p>检测结果 : ***  其它信息:***</p>
<h2>详细信息</h2>
<table border="1" width="40%" cellspacing='0' cellpadding='0'>
    <tr>
        <th>机柜号</th>
        <th>检测时间</th>
        <th>检测结果</th>
        <th>详细信息</th>
        <th>图片路径</th>
    </tr>
    {% for item in body %}
        <tr align='center'>
            <td>{{ item.cabID }}</td>
            <td>{{ item.shijian }}</td>
            <td>{{ item.final_result }}</td>
            <td>{{ item.info }}</td>
            <td><a href="#{{ item.shijian }}">{{ item.shijian }}</a></td>
        </tr>
    {% endfor %}
</table>
<h2>图片显示</h2>
{% for item in body %}
    <p>{{ item.shijian }}</p>
    <a name="{{ item.shijian }}"> <img src="{{ item.image_path }}" width="640"></a>
    <br>
{% endfor %}
</body>
</html>

2、python脚本

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ =

from jinja2 import Environment, FileSystemLoader
import time

def generate_html(body, starttime, stoptime):
    # 设置模板文件夹路径
    template_folder = "./"
    # 创建Jinja2环境
    env = Environment(loader=FileSystemLoader(template_folder))
    template = env.get_template('template.html')
    with open("result.html", 'w+', encoding='utf-8') as f:
        html_content = template.render(start_time=starttime,
                                       stop_time=stoptime,
                                       body=body)
        f.write(html_content)
        print(html_content)

if __name__ == "__main__":
    body = []
    result = {'cabID': 1, 'shijian': f"{time.strftime('%Y-%m-%d %H:%M:%S')}", 'final_result': "正常", 'info': "",
              'image_path': "test.png"}
    body.append(result)
    generate_html(body, f"{time.strftime('%Y-%m-%d %H:%M')}", f"{time.strftime('%Y-%m-%d %H:%M')}")

参考链接:
      https://docs.jinkan.org/docs/jinja2/      # jinja2官方文档
      https://www.cnblogs.com/noKing/p/8117461.html     # jinja自动补全
      https://www.cnblogs.com/wengzx/p/16837339.html     # python可视化库streamlit
      https://www.yii666.com/blog/428589.html      # python可视化库streamlit
      https://docs.streamlit.io/library/get-started/main-concepts      # streamlit库官方文档
      https://docs.python.org/zh-cn/3/library/webbrowser.html    # python webbrowser模块
      https://pyecharts.org/#/zh-cn/     # 使用pyecharts库生成图表
      https://www.cnblogs.com/kaerxifa/p/13035376.html      # 使用python dominate库生成html文档

posted @ 2023-09-01 15:04  風£飛  阅读(172)  评论(0)    收藏  举报