欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Flask如何結(jié)合Jinja2模板引擎返回渲染后HTML

 更新時(shí)間:2025年06月25日 10:02:30   作者:大霸王龍  
在 Flask 中結(jié)合 Jinja2 模板引擎返回渲染后的 HTML 是核心功能之一,本文主要介紹了詳細(xì)實(shí)現(xiàn)方法和最佳實(shí)踐,有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下

在 Flask 中結(jié)合 Jinja2 模板引擎返回渲染后的 HTML 是核心功能之一。以下是詳細(xì)實(shí)現(xiàn)方法和最佳實(shí)踐:

一、基礎(chǔ)模板渲染

1. 項(xiàng)目結(jié)構(gòu)準(zhǔn)備

myapp/
├── app.py          # Flask主程序
├── templates/      # 模板目錄
│   └── index.html  # Jinja2模板
└── static/         # 靜態(tài)資源(CSS/JS/圖片)

2. 基本渲染示例

# app.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html', 
                         title='首頁(yè)',
                         user={'name': '張三', 'age': 25})
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>
    <link href="{{ url_for('static', filename='css/style.css') }}" rel="external nofollow"  rel="stylesheet">
</head>
<body>
    <h1>歡迎, {{ user.name }}!</h1>
    {% if user.age >= 18 %}
        <p>您是成年人</p>
    {% else %}
        <p>您是未成年人</p>
    {% endif %}
</body>
</html>

二、高級(jí)模板技巧

1. 模板繼承(Layout系統(tǒng))

<!-- 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 %}子頁(yè)面{% endblock %}

{% block content %}
<h1>這是子頁(yè)面內(nèi)容</h1>
{% endblock %}

2. 宏(Macros)實(shí)現(xiàn)組件復(fù)用

<!-- 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}) }}

三、動(dòng)態(tài)數(shù)據(jù)與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動(dòng)態(tài)加載(推薦)

# 提供JSON API
@app.route('/api/data')
def api_data():
    return jsonify({'data': [4,5,6]})
// 前端通過(guò)fetch獲取
fetch('/api/data')
  .then(res => res.json())
  .then(data => {
      document.getElementById('output').innerHTML = 
          `服務(wù)器數(shù)據(jù): ${data.data.join(', ')}`;
  });

四、常見(jiàn)問(wèn)題解決方案

1. 緩存問(wèn)題

開(kāi)發(fā)時(shí)禁用緩存:

@app.after_request
def add_header(response):
    if 'Cache-Control' not in response.headers:
        response.headers['Cache-Control'] = 'no-store'
    return response

2. 處理表單數(shù)據(jù)

@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>

五、性能優(yōu)化建議

1.模板緩存(生產(chǎn)環(huán)境啟用):

app.config['TEMPLATES_AUTO_RELOAD'] = False  # 生產(chǎn)環(huán)境設(shè)為False

2.靜態(tài)文件版本控制

<link href="/static/css/style.css?v={{ config.VERSION }}" rel="external nofollow"  rel="stylesheet">

3.異步加載

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

六、安全注意事項(xiàng)

1.始終轉(zhuǎn)義變量

<!-- 安全 -->
<p>{{ user_input | escape }}</p>

<!-- 危險(xiǎn)!避免直接渲染HTML -->
<p>{{ user_input | safe }}</p> 

2.內(nèi)容安全策略(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, request

app = Flask(__name__)

@app.route('/search')
def search():
    query = request.args.get('q', '')
    results = []  # 這里替換為實(shí)際搜索邏輯
    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 %}

通過(guò)以上方法,您可以高效地在Flask中實(shí)現(xiàn):

  • 動(dòng)態(tài)HTML渲染
  • 前后端數(shù)據(jù)交互
  • 組件化開(kāi)發(fā)
  • 安全的內(nèi)容輸出

關(guān)鍵點(diǎn)是合理使用Jinja2的模板繼承、控制結(jié)構(gòu)和過(guò)濾器,同時(shí)注意安全性和性能優(yōu)化。

到此這篇關(guān)于Flask如何結(jié)合Jinja2模板引擎返回渲染后HTML的文章就介紹到這了,更多相關(guān)Flask Jinja2返回渲染后HTML內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Tensorflow與RNN、雙向LSTM等的踩坑記錄及解決

    Tensorflow與RNN、雙向LSTM等的踩坑記錄及解決

    這篇文章主要介紹了Tensorflow與RNN、雙向LSTM等的踩坑記錄及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • python 子類調(diào)用父類的構(gòu)造函數(shù)實(shí)例

    python 子類調(diào)用父類的構(gòu)造函數(shù)實(shí)例

    這篇文章主要介紹了python 子類調(diào)用父類的構(gòu)造函數(shù)實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-03-03
  • python文檔字符串(函數(shù)使用說(shuō)明)使用詳解

    python文檔字符串(函數(shù)使用說(shuō)明)使用詳解

    這篇文章主要介紹了python文檔字符串(函數(shù)使用說(shuō)明)使用詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07
  • Pytorch加載數(shù)據(jù)集的方式總結(jié)及補(bǔ)充

    Pytorch加載數(shù)據(jù)集的方式總結(jié)及補(bǔ)充

    Pytorch自定義數(shù)據(jù)集方法,應(yīng)該是用pytorch做算法的最基本的東西,下面這篇文章主要給大家介紹了關(guān)于Pytorch加載數(shù)據(jù)集的方式總結(jié)及補(bǔ)充,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-11-11
  • Python爬蟲之Selenium庫(kù)的使用方法

    Python爬蟲之Selenium庫(kù)的使用方法

    這篇文章主要介紹了Python爬蟲之Selenium庫(kù)的使用方法,幫助大家更好的理解和使用爬蟲,感興趣的朋友可以了解下
    2021-01-01
  • 關(guān)于Python元祖,列表,字典,集合的比較

    關(guān)于Python元祖,列表,字典,集合的比較

    下面小編就為大家?guī)?lái)一篇關(guān)于Python元祖,列表,字典,集合的比較。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-01-01
  • python如何刪除列為空的行

    python如何刪除列為空的行

    在本篇文章里小編給大家整理的是關(guān)于python刪除列為空的行方法,對(duì)此有需要的朋友們可以學(xué)習(xí)下。
    2020-07-07
  • python繪制立方體的方法

    python繪制立方體的方法

    這篇文章主要為大家詳細(xì)介紹了python繪制立方體的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • python如何實(shí)現(xiàn)excel數(shù)據(jù)添加到mongodb

    python如何實(shí)現(xiàn)excel數(shù)據(jù)添加到mongodb

    本文介紹了python是如何實(shí)現(xiàn)excel數(shù)據(jù)添加到mongodb,為了將數(shù)據(jù)導(dǎo)入mongodb,引入了pymongo,xlrd包,需要的朋友可以參考下
    2015-07-07
  • python中的decode()與encode()深入理解

    python中的decode()與encode()深入理解

    這篇文章主要介紹了python中的decode()與encode()函數(shù)詳解,本文通過(guò)實(shí)例代碼給大家講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-12-12

最新評(píng)論