Flask 6 模板2

NOTE

Jinja2提供了多种控制程序,可以用来改变模板的渲染流程。

1.在模板中使用条件控制语句:

templates/condition.html:

{% if user %}
    Hello, {{ user }}!
{% else %}
    Hello, Stranger!
{% endif %}

hello.py:

#!/usr/bin/env python

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('condition.html')

@app.route('/user/<name>')
def user(name):
    return render_template('condition.html', user=name)

if __name__ == '__main__':
    app.run(debug=True)

localhost:5000 :

Hello, wasdns!

2.在模板中渲染一组元素:

<ul>
    {% for comment in comments %}
        <li>{{ comment }}</li>
    {% endfor %}
</ul>

3.宏,类似函数:

{% macro render_comment(comment) %}
    <li>{{ comment }}</li>
{% endmacro %}

<ul>
    {% for comment in comments %}
        {{ render_comment(comment) }}
    {% endfor %}
</ul>

也可以将宏单独放在一个文件中,然后导入:

macros.html:

{% macro render_comment(comment) %}
    <li>{{ comment }}</li>
{% endmacro %}

demo.html:

{% import 'macros.html' as macros %}

<ul>
    {% for comment in comments %}
        {{ render_comment(comment) }}
    {% endfor %}
</ul>

4.继承:block标签定义的元素可以在衍生模板中进行修改。

base.html:

<html>
<head>
    {% block head %}
    <title>{% block title %}{% endblock %} - My Application</title>
    {% block end %}
</head>
<body>
    {% block body %}
    {% endblock %}
</body>
</html>

extend.html:

{% extends "base.html "%}

{% block title %}Index{% endblock %}
{% block head %}
    {{ super() }}
    <style>
    </style>
{% endblock %}
{% block body %}
<h1>Hello World!</h1>
{% endblock %}

super() => 获取基模板中原有内容。

2017/2/19

posted @ 2017-02-19 15:23  Wasdns  阅读(141)  评论(0编辑  收藏  举报