python3.7+flask+web学习笔记3

JInja2 模板引擎

  • 学习如何使用Flask的模板

  • 在模板中传递一个或者多个参数

  • 条件语句if和循环语句for在模板的使用

1.学习如何使用Flask的模板

新建立一个工程,或者是在原先的工程上面进行修改,为了节省时间,我用修改的方式进行学习;这样比较快一些。

模板建立2个html页面:

非常简单的页面;

2.在模板中传递一个或者多个参数

2.1传入一个参数的例子:

#encoding:utf-8
from flask import Flask
from flask import render_template
#定义apptest
apptest = Flask(__name__)

@apptest.route("/")
def index():
    return render_template("index.html")

@apptest.route("/user/<username>")

def user(username):
    return render_template("/user/user.html",name=username)

#程序主入口
if __name__ == '__main__':

    apptest.run()

运行结果

2.2多个参数的传递:通过修改index.html

代码增加getTime()和index() 修改

#获取当前时间
def getTime():
    now = datetime.datetime.now()
    otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
    return otherStyleTime

@apptest.route("/")
def index():
    title="我的首页的例子"
    auther="风清扬"
    myTime=getTime()

    return render_template("index.html", **locals()) ####注意红色部分,是传送多个参数的,那么html的页面赋值自己用这里定义的{{title}} {{auther}} {{myTime}} 

运行的结果,如下图

3.条件语句if和循环语句for在模板的使用

jinja2的if分支语句和for语句{% %}的方式进行,用一个随机数进行编写,随机数,1和0,效果图下图

增加一个随机数

#增加一个随机数
@apptest.route("/")
def index():
    title="我的首页的例子"
    auther="风清扬"
    myTime=getTime()
    randl= random.randint(0,1)   ###增加一个0和1的随机数,1为有效,0为无效

    return render_template("index.html", **locals())

 

发布了134 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/keny88888/article/details/103578124