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

软件测试中,对结果数据如何进行展示呢?
工作中一般会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 为模板文件

使用Python写HTML 文件使用jinja2中的模板_第1张图片

模板文件:

    <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

你可能感兴趣的:(python)