感谢那些伴你成长的人
python 中的 jinja2 的基本学习和使用
test.j2 文件内容
{ "customer": "{{shopify_order.customer}}", "orderService": "ServiceName", "name":"{{shopify_order.names or ''}}" }这是常用的
{% for xxx in 集合 %}
{% endfor%}
{% if kenny.sick %}
Kenny is sick.
{% elif kenny.dead %}
You killed Kenny! You bastard!!!
{% else %}
Kenny looks okay --- so far
{% endif %}
python 代码实现
from jinja2 import Environment,FileSystemLoader import json import ast shopify_order = {} shopify_order['customer']='Gavin' name_list = ['Gavin','Peter','Zero'] shopify_order['name'] = name_list env = Environment(loader=FileSystemLoader('D:\python_DaiMa\python_learn_github\python_exercise_record\jinja2r\json')) template = env.get_template('test.j2') content = template.render(shopify_order=shopify_order) print(content) dict_str = ast.literal_eval(content) print(dict_str)
运行结果的使用
{
"customer": "Gavin",
"orderService": "ServiceName",
"name":""
}
{'customer': 'Gavin', 'orderService': 'ServiceName', 'name': ''}
一些基本的使用转换
参考文章地址 : http://www.imooc.com/article/36030