Jinja2.template渲染两种常见用法
template是字符串
>>> 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文本中
<h1>username:</h1>{{ name }}
<h1>age:</h1>{{ age }}
然后我们需要定义一个dict
ds_conf = {"name" : "wyett", "age" : 20 }
渲染脚本
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
静水流深