Jinja2.template渲染兩種常見用法

template是字符串html

>>> import os, jinja2
>>> html = u'''<h1>username:</h1>{{ name }}
... <h1>age:</h1>{{ age }}'''
>>> _t = jinja2.Template(html, trim_blocks=True)
>>> _text = _t.render(name='wyett',age=20)
>>> _text = _text.encode('utf-8')
>>> print _text
<h1>username:</h1>wyett
<h1>age:</h1>20
>>> 

template存放在json文本中json

<h1>username:</h1>{{ name }}
<h1>age:</h1>{{ age }}

而後咱們須要定義一個dictspa

ds_conf = {"name" : "wyett",
                 "age" : 20
                }

渲染腳本code

TemplateLoader = jinja2.FileSystemLoader(os.path.abspath('.'))
TemplateEnv = jinja2.Environment(loader=TemplateLoader)
template = TemplateEnv.get_template('html.json.j2')
dsconf = template.render(ds_conf)
print dsconf
相關文章
相關標籤/搜索