記一次Python 中jinja2 的基本操作

                        感謝那些伴你成長的人


 

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章