Flask框架框架Jinjia模板常用语法总结模板常用语法总结
本文实例总结了Flask框架Jinjia模板常用语法。分享给大家供大家参考,具体如下:
1. 变量表示变量表示
{{ argv }}
2. 赋值操作赋值操作
{% set links = [
('home',url_for('.home')),
('service',url_for('.service')),
('about',url_for('.about')),
] %}
3. if判断判断
{% if not loop.first %}|{% endif %}
4. for 循环循环
{% for label,link in links %}
{% if not loop.first %}|{% endif %}
<a href="{{%20link%20}}" rel="external nofollow" >{{ label }}</a>
{% endfor %}
5. 定义测试函数定义测试函数
上面 loop.first 就是一个测试函数,这个我们也可以自定义
定义是在Sample.py 里定义的,current_link是HTML中可使用测试函数名称(可选)
@app.template_test('current_link')
def is_current_link(link):
return link == request.path
HTML中,使用例子
<body>
{% set links = [
('home',url_for('.home')),
('service',url_for('.service')),
('about',url_for('.about')),
] %}
<nav>
{% for label,link in links %}
{% if not loop.first %}|{% endif %}
<a href="{% if link is current_link %}#
{% else %}
{{%20link%20}}
{% endif %}
">{{ label }}</a>
{% endfor %}
</nav>
</body>
6. 块块block
Flask强大的地方就可以引用模板,而且非常方便。
这里不得不介绍block这个概念。