当前位置: 首页 > news >正文

Flask 中结合 Jinja2 模板引擎返回渲染后的 HTML

在 Flask 中结合 Jinja2 模板引擎返回渲染后的 HTML 是核心功能之一。以下是详细实现方法和最佳实践:


一、基础模板渲染

1. 项目结构准备
myapp/
├── app.py          # Flask主程序
├── templates/      # 模板目录
│   └── index.html  # Jinja2模板
└── static/         # 静态资源(CSS/JS/图片)
2. 基本渲染示例
# app.py
from flask import Flask, render_templateapp = Flask(__name__)@app.route('/')
def home():return render_template('index.html', title='首页',user={'name': '张三', 'age': 25})
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head><title>{{ title }}</title><link href="{{ url_for('static', filename='css/style.css') }}" rel="stylesheet">
</head>
<body><h1>欢迎, {{ user.name }}!</h1>{% if user.age >= 18 %}<p>您是成年人</p>{% else %}<p>您是未成年人</p>{% endif %}
</body>
</html>

二、高级模板技巧

1. 模板继承(Layout系统)
<!-- templates/layout.html -->
<html>
<head>{% block head %}<title>{% block title %}{% endblock %}</title>{% endblock %}
</head>
<body>{% block content %}{% endblock %}
</body>
</html>
<!-- templates/page.html -->
{% extends "layout.html" %}{% block title %}子页面{% endblock %}{% block content %}
<h1>这是子页面内容</h1>
{% endblock %}
2. 宏(Macros)实现组件复用
<!-- templates/macros.html -->
{% macro render_user(user) %}
<div class="user-card"><h3>{{ user.name }}</h3><p>年龄: {{ user.age }}</p>
</div>
{% endmacro %}
<!-- 使用宏 -->
{% from "macros.html" import render_user %}{{ render_user({'name': '李四', 'age': 30}) }}

三、动态数据与JS交互

1. 直接传递JSON到JS
# Flask路由
@app.route('/data')
def get_data():return render_template('data.html', items=[1, 2, 3],config={'debug': True})
<script>
const APP_CONFIG = {{ config | tojson | safe }};
const ITEMS = {{ items | tojson | safe }};console.log(APP_CONFIG.debug); // true
ITEMS.forEach(item => console.log(item));
</script>
2. AJAX动态加载(推荐)
# 提供JSON API
@app.route('/api/data')
def api_data():return jsonify({'data': [4,5,6]})
// 前端通过fetch获取
fetch('/api/data').then(res => res.json()).then(data => {document.getElementById('output').innerHTML = `服务器数据: ${data.data.join(', ')}`;});

四、常见问题解决方案

1. 缓存问题

开发时禁用缓存:

@app.after_request
def add_header(response):if 'Cache-Control' not in response.headers:response.headers['Cache-Control'] = 'no-store'return response
2. 处理表单数据
@app.route('/submit', methods=['POST'])
def submit():username = request.form.get('username')return render_template('result.html', username=username)
<form method="POST" action="/submit"><input type="text" name="username"><button type="submit">提交</button>
</form>

五、性能优化建议

  1. 模板缓存(生产环境启用):

    app.config['TEMPLATES_AUTO_RELOAD'] = False  # 生产环境设为False
    
  2. 静态文件版本控制

    <link href="/static/css/style.css?v={{ config.VERSION }}" rel="stylesheet">
    
  3. 异步加载

    <script defer src="{{ url_for('static', filename='js/app.js') }}"></script>
    

六、安全注意事项

  1. 始终转义变量

    <!-- 安全 -->
    <p>{{ user_input | escape }}</p><!-- 危险!避免直接渲染HTML -->
    <p>{{ user_input | safe }}</p> 
    
  2. 内容安全策略(CSP)

    @app.after_request
    def add_csp(response):response.headers['Content-Security-Policy'] = "default-src 'self'"return response
    

七、完整工作流程示例

# app.py
from flask import Flask, render_template, requestapp = Flask(__name__)@app.route('/search')
def search():query = request.args.get('q', '')results = []  # 这里替换为实际搜索逻辑return render_template('search.html',query=query,results=results)if __name__ == '__main__':app.run(debug=True)
<!-- templates/search.html -->
{% extends "layout.html" %}{% block content %}
<form action="/search"><input type="text" name="q" value="{{ query }}"><button>搜索</button>
</form><ul>{% for item in results %}<li>{{ item }}</li>{% endfor %}
</ul>
{% endblock %}

通过以上方法,您可以高效地在Flask中实现:

  • 动态HTML渲染
  • 前后端数据交互
  • 组件化开发
  • 安全的内容输出

关键点是合理使用Jinja2的模板继承、控制结构和过滤器,同时注意安全性和性能优化。

相关文章:

  • SiteAzure4.x 版本 访问html静态页文件出现404错误
  • 【AS32系列MCU调试教程】基础配置:Eclipse项目与工具链的优化
  • 基于STM32汽车温度空调控制系统
  • 使用 C/C++的OpenCV 裁剪 MP4 视频
  • SQL进阶之旅 Day 29:NoSQL结合使用策略
  • 重启杀手--误操作梳理
  • CHI协议验证中的异常及边界验证
  • Vue 动态设置当前页面标题和图标
  • 【狂飙AGI】第3课:大模型时代前沿技术
  • 【新能源汽车技术全景解析:构建智能出行新生态】
  • 力扣:基本计算器
  • Nodejs特训专栏-基础篇:1. Node.js环境搭建与项目初始化详细指南
  • Vue3+vite 路由实现
  • Django框架认证系统默认在登录成功后尝试重定向到/accounts/profile/
  • 埃隆·马斯克宣布特斯拉Robotaxi自动驾驶出租车服务将于6月22日在奥斯汀“试运行”启动
  • 网络层协议:IP
  • 医疗集团级“人-机-料-法-环”全流程质控的医疗数据质控方案分析
  • 在QtCreator中使用GitHubCopilot
  • 如何确定某个路由器的路由表?(计算机网络)
  • vue 如何配置使用 env文件
  • 经销商城建站/百度投诉中心人工电话号码
  • wordpress可以做电影站/谷歌搜索引擎怎么才能用
  • 动漫制作与设计专业/seo排名点击器
  • 公司的网站建设 交给谁做更好些/千锋教育学费
  • 织梦网站默认密码/hs网站推广
  • 加盟餐饮的网站建设/神秘网站