Templates中的标签if

1.什么是标签
  每个标签标示的是不同的服务器端的功能
2.常用标签
  1. if 标签
    1.基本if结构
      {% if 条件 %}
      % endif %}

    2.if ... else ... 结构
      {% if 条件 %}
        满足条件时要运行的代码
      {% else %}
        不满足条件时要运行的代码
      {% endif %}
    3.if ... elif ... elif ... else
      {% if 条件1 %}
        满足条件1,要运行的代码
      {% elif 条件2 %}
        满足条件2,要运行的代码
      {% elif 条件3 %}
        满足条件3,要运行的代码
      {% else %}
        以上条件都不满足的时候,要运行的代码
      {% endif %}

举个例子:

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'


# 多个route,有助于后面的if判断
@app.route("/zengsf")
@app.route("/zengsf/<name>")
def zengsf(name=None):
    return render_template("01-if.html", uname = name)


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

01-if.html中,这里的else中利用到了反向url解析

{% if uname %}
        <h1>{{ uname }}</h1>
    {% else %}
        <h1>
            <a href="{{ url_for('hello_world')}}">shouye</a>
        </h1>
    {% endif %}
原文地址:https://www.cnblogs.com/zengsf/p/9932818.html