像SpringBoot一样使用Flask - 2.静态资源访问及模版

一、安装并导入 render_template

功能:渲染/加载模板,一般是html页面

参数:函数的第一个参数是模板的文件名,必填,后面的参数都是键值对,表示模板中变量对应的值,非必填 (不填界面也不会展示成变量名,只是不填则不渲染)。

二、修改app主入口配置,类似SpringBoot的yaml配置。

python 复制代码
from flask import Flask, render_template

app = Flask(__name__,
            static_url_path='/',  # 配置静态文件的访问 url 前缀)
            static_folder='static',  # 配置静态文件的文件夹
            template_folder='templates'  # 配置模板文件的文件夹
            )

static_url_path和static_folder写上去,可以在引用css/js可以更好的用/代替写相对路径,不用看到../../类似的写法

三、测试

增加测试请求/index

python 复制代码
name = '小明'
year = '2024'


@app.route('/index')
def happy_new_year():
    return render_template('test/index.html', name=name, year=year)

controller

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><title>{{ year }} 新年快乐</title>
</head>
<link rel="stylesheet" href="/test/index.css">
<body>
    <h2 id="indexId">你好 {{ name }} , 祝你 {{ year }} 平安喜乐,玩好Flask</h2>
</body>
</html>

index.html

css 复制代码
#indexId{
    color: aquamarine;
}

index.css

目录结构

四、运行

五、总结

这个很像springboot里面的Thymeleaf。重点在配置上,避免后续static路径,项目一增加,看着有点乱。建议写上去,少一点../../,增加代码可读性

相关推荐
tan180°3 小时前
MySQL表的操作(3)
linux·数据库·c++·vscode·后端·mysql
优创学社24 小时前
基于springboot的社区生鲜团购系统
java·spring boot·后端
why技术4 小时前
Stack Overflow,轰然倒下!
前端·人工智能·后端
幽络源小助理4 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
烛阴5 小时前
简单入门Python装饰器
前端·python
好开心啊没烦恼5 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
面朝大海,春不暖,花不开5 小时前
使用 Python 实现 ETL 流程:从文本文件提取到数据处理的全面指南
python·etl·原型模式
ai小鬼头5 小时前
AIStarter如何助力用户与创作者?Stable Diffusion一键管理教程!
后端·架构·github
简佐义的博客5 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang