美文网首页
学习Flask002:惯例 templates 和 static

学习Flask002:惯例 templates 和 static

作者: 我的小小笔尖 | 来源:发表于2022-04-13 09:24 被阅读0次

按照惯例,模板和静态文件存放在应用的 Python 源代码树的子目录中,名称分别为 templates 和 static 。惯例是可以改变的,但是你大可不必 改变,尤其是刚起步的时候。

1.我们在项目目录下分别创建两个目录templates 和 static
2.我们在static目录下放一个图片test.jpg,可以通过url直接访问这张图片
static.JPG
3.在templates目录下创建模板文件test.html(前端)

文件内容如下:

<html>
    <head>
        <title>{{title}}</title>
    </head>
    <body>
        <div>Hello {{user.name}},欢迎来到Flask世界!</div>
        <div>你今年{{user.age}}岁了!</div>
    </body>
</html>

其中{{title}}、{{user.name}}和{{user.age}}是变量,根据实际给的值显示。
模板的用途就是负责前端显示。
使用模板的好处就是:前端只需要设计显示页面即可,不需要处理后端的业务逻辑。前端不关心后台的数据如何得到,只关心数据在页面如何展示。

4.配置route(后端)
@app.route('/testtemplate')
def testtemplate():
    user = {
        "name": "张三",
        "age":"18"
    }
    return render_template('test.html', title='我是页面标题', user=user)

test.html是模板文件,title和user是传递的参数,其中user是个对象,包含name和age两个属性。

别忘记引用模板函数render_template:

from flask import render_template
5.启动flask项目,访问
title.JPG

相关文章

网友评论

      本文标题:学习Flask002:惯例 templates 和 static

      本文链接:https://www.haomeiwen.com/subject/yobosrtx.html