Jinja2模块生成html

1、html模板

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<html align='left'>
<h1>巡检报告</h1>
<body>
<h2>报告综述</h2>
<p>巡检地点 : 机房&nbsp;&nbsp;开始时间 : {{ start_time }}&nbsp;&nbsp;结束时间 : {{ stop_time }}  </p>
<p>检测结果 : ***&nbsp;&nbsp;其它信息:***</p>
<h2>详细信息</h2>
<table border="1" width="40%" cellspacing='0' cellpadding='0' align='left'>
    <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>
        </tr>
    {% endfor %}
</table>
</body>
</html>

2、python代码

from jinja2 import Environment, FileSystemLoader


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+') as f:
        html_content = template.render(start_time=starttime,
                                       stop_time=stoptime,
                                       body=body)
    print(html_content)
    f.write(html_content)


if __name__ == "__main__":
    body = []
    result = {'cabID': 1, 'shijian': 2019, 'final_result': "正常", 'info': ""}
    body.append(result)
    generate_html(body, 2019, 2019)

参考链接:
      https://docs.jinkan.org/docs/jinja2/templates.html#variables
      https://blog.csdn.net/zong596568821xp/article/details/100522584     # Python之jinja2模板引擎生成HTML
      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模块

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