cat temp.temp hello {{ name }} {% for love in love_sports %} my loves sport is {{ love }} {% endfor %} {% if is_boy %} i am a good boy {% else %} i am a good girl {% endif %}
# -*- coding: UTF-8 -*- from jinja2 import Template with open("temp.temp",'r') as f: template_content = f.read() template = Template(template_content) content = template.render( name='John Doe', love_sports = ["basketall","football","paiball"], is_boy=True ) print(content)
#输出 :
hello John Doe
my loves sport is basketall
my loves sport is football
my loves sport is paiball
i am a good boy
使用 Environment 来初始化对象,并用它来加载模板,
jinja2支持两种加载模板的方式
- PackageLoader:包加载器
- FileSystemLoader:文件系统加载器
from jinja2 import Environment, FileSystemLoader env = Environment( loader = FileSystemLoader('/home/templates') ) template = env.get_template('temp.temp') content = template.render( name='John Doe', love_sports = ["basketall","football"], is_boy=True ) print content
[root@jinkang-e2elog app]# cat testabcd.py from jinja2 import Environment, PackageLoader env = Environment(loader=PackageLoader('testabcd','templates')) template = env.get_template('temp.temp') content = template.render( name='John Doe', love_sports = ["basketall","football"], is_boy=True ) print content