使用Python写HTML 文件使用jinja2中的模板

来源:互联网 发布:天地诸神翅膀数据 编辑:程序博客网 时间:2024/05/21 23:31

软件测试中,对结果数据如何进行展示呢?
工作中一般会1.发邮件出来2.将结果保存在html文件中,将链接附在邮件中。

之前使用的方法比较挫,使用Python语句一行一行进行拼凑,常常需要在Python代码中写一些CSS样式语句,后来后然发现,原来Python的 jinja2 模块早已支持Python使用模版进行HTML编写,使用之后,真是方便,样式和数据分离,代码也清爽了不少。

如果有过web开发经验的人,理解应该不难,但是对于使用Python写写小工具的同学来说,真是福音啊~~

直接贴上自己的代码:

首先需要安装jinja2模块:

from jinja2 import Environment, PackageLoader

env = Environment(loader=PackageLoader('analisys', 'templates'))template = env.get_template('report.html')html_content = template.render(summary = summ_info , details=detail_info)

其中analisys 为代码所在包名
templates\report.thml 为模板文件

这里写图片描述

模板文件:

    <section>        <table border="1" cellspacing=0 cellpadding=2 bordercolor=#505050>            <tr>                <th></th>                <th>变更总数</th>                <th>新增</th>                <th>删除</th>                <th>修改</th>            </tr>            {% for group in summary %}                <tr>                    <th>{{ group[0] }}</th>                    <td><center>{{ group[1] }}</center></td>                    <td><center>{{ group[2] }}</center></td>                    <td><center>{{ group[3] }}</center></td>                    <td><center>{{ group[4] }}</center></td>                </tr>            {% endfor %}            </table>    </section>

其他信息参考:
http://www.jb51.net/article/87718.htm
http://blog.csdn.net/wangjianno2/article/details/51044780