Flask模板渲染

五、flask模板渲染

py文件:

from flask import Flask,render_template,Markup
app = Flask(__name__)
app.debug = True


USERS = {
    1:{'name':'张三','age':18,'gender':'男','text':"道路千万条"},
    2:{'name':'李四','age':28,'gender':'男','text':"安全第一条"},
    3:{'name':'王五','age':18,'gender':'女','text':"行车不规范"},
}

def func1(arg,tank):
    return Markup(f"<h1>饼哥正帅,{arg} is sb {tank} is same as {arg}</h1>")

@app.route("/")
def index():
    # data = {
    #     "user" :USERS,
    #     "name": "jason"
    # }
    return render_template("index.html",user = USERS,name="jason",ht1 = func1,ht="<h1>饼哥正帅</h1>")
    #return render_template("index.html",**data)




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

5.1 变量的循环

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1> 我是html</h1>
<table>
{% for k,v in user.items() %}
   <tr>
       <td>{{ k }}</td>
       <td>{{ v.name }}</td>
       <td>{{ v['name'] }}</td>
       <td>{{ v.get('name') }}</td>
       <td>{{url_for("index")}}</td>
   </tr>
{% endfor %}
</body>
</html>

5.2 逻辑判断

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>用户列表</h1>
    <table>
        {% if name %}
          <h1>Hello {{ name }}!</h1>
        {% else %}
          <h1>Hello World!</h1>
        {% endif %}
    </table>
</body>
</html>

5.3 执行函数,传参数

比django中多可以加括号,执行函数,传参数

from flask import Flask,render_template,Markup
app = Flask(__name__)
app.debug = True



def func1(arg,tank):
    return Markup(f"<h1>饼哥正帅,{arg} is sb {tank} is same as {arg}</h1>")

@app.route("/")
def index():
    # data = {
    #     "user" :USERS,
    #     "name": "jason"
    # }
    return render_template("index.html",ht1 = func1,ht="<h1>饼哥正帅</h1>")



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

html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

{{ ht|safe}}
{{ht1("jaosn","tank")}}  // 传参数
</body>
</html>
posted @ 2020-03-19 16:32  Jeff的技术栈  阅读(187)  评论(0编辑  收藏  举报
回顶部