一周学会Flask3 Python Web开发-Jinja2模板继承和include标签使用

锋哥原创的Flask3 Python Web开发 Flask3视频教程:

2025版 Flask3 Python web开发 视频教程(无废话版) 玩命更新中~_哔哩哔哩_bilibili

不管是开发网站还是后台管理系统,我们页面里多多少少有公共的模块。比如博客网站,就有公共的头部,菜单和底部栏。每个页面都有,我们往往要抽取出这些公共模块,然后统一维护。JinJa2提供了模板继承和include标签。

我们先把顶部信息和菜单抽取新建一个header.html放templates下:

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>头部,菜单</p>
</body>
</html>

同理 底部信息页抽取新建一个footer.html

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>底部</p>
</body>
</html>

我们再新建一个公共的父模版base.html,其他子模板继承即可,共同部分比如header,footer继承下来,不同的部分自己实现。这里可以通过block标签在父类先预留一块。然后子类实现block即可。include标签引入公共模块。

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}默认标题{% endblock %}</title>
</head>
<body>
{% include 'header.html' %}
{% block content %}
    默认内容
{% endblock %}
{% include 'footer.html' %}
</body>
</html>

新建博客首页index.html,通过extends继承base.html,以及重写实现block title和content

复制代码
{% extends "base.html" %}
{% block title %}
    博客首页
{% endblock %}
{% block content %}
    博客列表
{% endblock %}

同理博客帖子页面detail.html

复制代码
{% extends "base.html" %}
{% block title %}
    博客帖子
{% endblock %}
{% block content %}
    博客帖子
{% endblock %}

user.py里实现下视图函数:

复制代码
@user_bp.route('/index')
def index():
    return render_template('index.html')


@user_bp.route('/detail')
def detail():
    return render_template('detail.html')

我们测试下:

相关推荐
敏编程2 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪2 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook3 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田15 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪19 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽19 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战20 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python