Jinja2模板的控制结构

2017-04-26  本文已影响36人  Vcns

基本来自《flask web开发》。

1.判断结构 if...else

  • 模板中(user.html):
{% if name %}
        Hello, {{name}}!
{% else %}
        Hello, stranger!
{% endif %}
return render_template('user.html', name = value)

2.循环结构 for

  • 模板(comment.html):
{% for comment in comments %}
        <li>
            {{comment}}
        </li>
    {% endfor %}

*视图函数中:

@app.route('/comment/<number>')
def comment(number):
    comment_list = range(number)
    return render_template('comment.html', comments = comment_list)

3.宏 macro

它就是函数,只是写法有点不同

{% macro funciton(arg) %}
    pass
{%  endmacro %}

等价于:

def function(arg):
    pass
{% import 'macros.html' as func %}
{% include 'base.html' %}

「这俩的差异主要在于,import是引入的宏,或者说是代码。」
「而include则是引入的文件。」

{% exdents '<path>' %}

<path>就是要继承的base.html的路径。本地一般用相对,网络用绝对。

上一篇 下一篇

猜你喜欢

热点阅读