jinja2模板引擎生成HTML
0 背景
在之前的文章中,我介紹過《Python之生成HTML文件》以及《HTML零基礎入門教程(詳細)》,手動生成了html文件,在實際使用的時候,我們完全可以套用模板文件來生成,免去了一條一條手寫的麻煩。關於python的模板引擎有很多種類,本文選擇的是比較常用的一種jinja2,接下來對該引擎的使用做一個介紹。
1 jinja2介紹
Jinja2 是一個現代的,設計者友好的,仿照 Django 模板的 Python 模板語言。 它速度快,被廣泛使用,並且提供了可選的沙箱模板執行環境保證安全,關於jinja2的文檔介紹。
安裝方法
sudo pip install jinja2
2 模板文件
接下來製作一個模板文件template.html,直接給代碼(超鏈接形式)
<meta http-equiv="Content-Type"content="text/html;charset=utf-8">
<html align='left'>
<h1>巡檢報告</h1>
<body>
<h2>報告綜述</h2>
<p>巡檢地點 : 機房 開始時間 : {{start_time}} 結束時間 : {{stop_time}} </p>
<p>檢測結果 : *** 其它信息:***</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>
<td><a href={{item.image_path}}>圖片</a> </td>
</tr>
{% endfor%}
</table>
</body>
</html>
3 測試方法
我們寫一個腳本程序,用來調用上述模板,生成指定的結果文件result.html
from jinja2 import Environment, FileSystemLoader
def generate_html( body, starttime, stoptime):
env = Environment(loader=FileSystemLoader('./'))
template = env.get_template('template.html')
with open("result.html",'w+') as fout:
html_content = template.render(start_time=starttime ,
stop_time=stoptime,
body=body)
fout.write(html_content)
if __name__ == "__main__":
body = []
result = {'cabID':1, 'shijian':2019, 'final_result':"正常", 'info':"無",
'image_path':"test.jpg"}
body.append(result)
generate_html(body, 2019, 2019)
運行後即可生成result.html文件如下
-------------------------2019/9/9更新----------------------------------------
上述使用的是超鏈接的形式進行圖片顯示,實際使用時不太方便,接下來使用錨點的方法來將圖片和結果顯示在一個頁面,代碼如下
<meta http-equiv="Content-Type"content="text/html;charset=utf-8">
<html align='left'>
<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>