jinja2 模板使用

task

有时候需要把数据(比如csv,或者\t分割)转换成html,方便查看。

jinja安装

pip install Jinja2
doc: http://docs.jinkan.org/docs/jinja2/index.html

过程

demo数据

1,2,3,4,5
6,7,8,9,10

把这两行数据渲染在表格里

  1. 创建your_template.html


    
        
            format
        
        
        
    
    
        
            {% for item in data %}
            
            {% endfor %}
        
mt flow 总消费 关闭消费 关闭占比 打开占比
{{ item[0] }} {{ item[1] }} {{ item[2] }} {{ item[3] }} {{ item[4] }} {{ item[5] }}
  1. html生成脚本gen_html.py
 # encoding=utf-8
 import sys
 from jinja2 import Environment, FileSystemLoader

 env = Environment(loader=FileSystemLoader('./', encoding='utf-8'))

 data = []
 with open('./data') as f:
     for line in f:
         line = line.decode('gb18030', 'ignore').strip()
         cols = line.split(u'\t')
         data.append(cols)

 template = env.get_template('your_template.html')
 html = template.render(date=date, encoding='utf-8', data=data)  # unicode string
 print >> sys.stdout, html.encode('utf-8', 'ignore')
  1. email
 python gen_html.py > temp.html

 email_to="[email protected]"
 /usr/lib/sendmail -t <<< "To: $email_to
 From: [email protected]
 Subject: demo
 Content-type: text/html; charset=utf-8
 $(cat temp.html)
 "

你可能感兴趣的:(jinja2 模板使用)