demo.py
from jinja2 import Environment,FileSystemLoader
import os
if __name__ == "__main__":
dir=os.getcwd()
env = Environment(loader=FileSystemLoader(dir),trim_blocks=True)
tpl=env.get_template('hello.html')
str=tpl.render({'name':'我爱中国','title':'这是一个标题'
,'qrys':[{'name':'张三','url':'http2'},{'name':'fks','url':'rurrll'}]
,'daxin':{'safe':1}
,'encoding':'utf-8'})
print(str)
hello.html
hello,变量设置:{}.{}
{% for user in qrys %}
<li><a href="{{ user.url }}">{{ user.name }}</a></li>
{% endfor %}
{% if daxin.safe %}
daxin is safe.
{% elif daxin.dead %}
daxin is dead
{% else %}
daxin is okay
{% endif %}
{% for key,value in qrys %}
<dt>{{ key }}</dt>
<dd>{{ value}}</dd>
{% endfor %}
{# 这是一个注释 #}
name | 说明 | |||
---|---|---|---|---|
loop.index | 从1开始 | |||
loop.index0 | 从0开始 | |||
loop.revindex | 倒序 | |||
loop.first | ||||
loop.last | ||||
loop.length | ||||
loop.cycle | ||||
loop.depth | ||||
loop.depth0 | ||||
#jinja2手册
https://www.w3cschool.cn/yshfid/
#jinja2模板语法介绍
https://www.cnblogs.com/dachenzi/p/8242713.html