from jinja2 import Template
## ex1
t = Template("hello {{person}}")
msg = t.render(person="bob")
print(msg) # hello bob
## ex2
t = Template("My favorite numbers : {% for n in range(1, 5)%} {{n}} {% endfor %}")
msg = t.render() # 'My favorite numbers : 1 2 3 4 '
## ex3
t = Template("my name is {{name}} and i am {{age}}")
msg = t.render(name="jsh", age=24)
print(msg) # my name is jsh and i am 24
## ex4
t = Template("i have a dict {{mydict}}")
msg = t.render(mydict={"a":1, "b":2})
print(msg) # i have a dict {'a': 1, 'b': 2}
## ex5
t = Template("this is a test msg")
msg = t.render()
print(msg) # this is a test msg
通过render来渲染得到最终的输出
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def getAge(self):
return self.__age
def getName(self):
return self.__name
p = Person('jsh', 24)
tm = Template("my name is {{p.getName()}} and I am {{p.getAge()}}")
msg = tm.render(p=p)
print(msg) # my name is jsh and I am 24
p.name和p[‘name’]都可以访问字典中的数据
person = {'name':'jsh', 'age':24}
t1 = Template("my name is {{p.name}} and i am {{p.age}}")
t2 = Template("my name is {{p['name']}} and i am {{p['age']}}")
msg = t1.render(p=person)
msg2 = t2.render(p=person)
print(msg) # my name is jsh and i am 24
print(msg2) # my name is jsh and i am 24
可以使用raw, endraw对Jinja定界符进行专业
data = """
{% raw %}
his name is {{name}}
{% endraw %}
"""
tm = Template(data)
msg = tm.render(name='jsh')
print(msg) # his name is {{name}}
可以看出,通过使用raw,endeaw, 对Jinja的{{}}进行了专业,输出了原始的内容
为了对<或者>符号进行转义,可以使用过滤器或者escape函数
from jinja2 import escape
data = ' this is a sunny day '
tm = Template("{{data | e}}")
msg = tm.render(data=data)
print(msg) # <a> this is a sunny day </a>
print(escape(data)) # <a> this is a sunny day </a>
过滤器通过|符号使用,通过使用e过滤器, <和>符号被转义
escape函数有相同的效果
persons = [
{"name":'alice', 'age':10},
{"name":"bob", 'age':11},
{"name":"cnady", 'age':12},
{"name":"dandy", 'age':13}
]
template = "{% for person in persons%} {{person.name}} {{person.age}} {%endfor%}"
t = Template(template)
msg = t.render(persons=persons)
print(msg) # alice 10 bob 11 cnady 12 dandy 13
在上面的例子中,我们使用for表达式对persons进行迭代,显示name和age。
template = "{% for person in persons%} {% if person.age < 13 %}{{person.name}} {{person.age}} {%endif%}{%endfor%}"
t = Template(template)
msg = t.render(persons=persons)
print(msg) # alice 10 bob 11 cnady 12
通过条件判断语句person.age<13进行判断, 注意{% if %}和{% endif %}
过滤器可以用来对数据进行修改,例如sum filter可以对数据求和, escape filter可以对数据进行转义,sort filter可以对数据进行排序, default filter 可以给数据提供默认值
# sum filter
cars = [
{'name':'audi', 'price':10},
{'name':'skoda', 'price':13},
{'name':'volvo', 'price':44}
]
template = "the sum of car prices is {{cars|sum(attribute='price')}}"
tm = Template(template)
msg = tm.render(cars=cars)
print(msg) # the sum of car prices is 67
# default filter
template = "hello {{name|default('jsh')}}"
tm = Template(template)
msg = tm.render()
print(msg) # hello jsh
msg = tm.render(name='bob')
print(msg) # hello bob
更多内容请见官方文档:https://jinja.palletsprojects.com/en/master/