最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python中Flask模板的使用與高級(jí)技巧詳解

 更新時(shí)間:2025年05月04日 08:23:34   作者:碼農(nóng)阿豪@新空間  
在Web開發(fā)中,直接將HTML代碼寫在Python文件中會(huì)導(dǎo)致諸多問題,Flask內(nèi)置了Jinja2模板引擎,完美解決了這些問題,下面我們就來看看Flask模板的具體應(yīng)用吧

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

1.1 為什么需要模板引擎

在Web開發(fā)中,直接將HTML代碼寫在Python文件中會(huì)導(dǎo)致諸多問題:

  • 代碼難以維護(hù)
  • 前后端耦合嚴(yán)重
  • 無法復(fù)用HTML組件
  • 缺乏邏輯控制能力

Flask內(nèi)置了Jinja2模板引擎,完美解決了這些問題。

1.2 第一個(gè)模板渲染示例

首先創(chuàng)建項(xiàng)目結(jié)構(gòu):

myapp/
├── app.py
└── templates/
    └── index.html

app.py內(nèi)容:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    user = {'username': '張三', 'age': 25}
    posts = [
        {'title': '第一篇', 'content': '內(nèi)容1'},
        {'title': '第二篇', 'content': '內(nèi)容2'}
    ]
    return render_template('index.html', user=user, posts=posts)

if __name__ == '__main__':
    app.run(debug=True)

templates/index.html內(nèi)容:

<!DOCTYPE html>
<html>
<head>
    <title>{{ user.username }}的主頁</title>
</head>
<body>
    <h1>歡迎, {{ user.username }}!</h1>
    <p>年齡: {{ user.age }}</p>
    
    <h2>文章列表</h2>
    <ul>
        {% for post in posts %}
        <li>{{ post.title }} - {{ post.content }}</li>
        {% endfor %}
    </ul>
</body>
</html>

1.3 模板渲染原理

render_template()函數(shù)的工作流程:

  • 在templates目錄查找指定模板文件
  • 解析模板中的變量和邏輯
  • 將上下文變量傳入模板
  • 生成最終HTML響應(yīng)

二、模板訪問對(duì)象屬性

2.1 訪問字典屬性

<p>用戶名: {{ user['username'] }}</p>
<p>年齡: {{ user.get('age', 18) }}</p>  <!-- 帶默認(rèn)值 -->

2.2 訪問對(duì)象屬性

假設(shè)我們有一個(gè)User類:

class User:
    def __init__(self, username, email):
        self.username = username
        self.email = email

模板中可以這樣訪問:

<p>用戶名: {{ user.username }}</p>
<p>郵箱: {{ user.email }}</p>

2.3 訪問列表和元組

<p>第一篇文章: {{ posts[0].title }}</p>
<p>最后一篇文章: {{ posts[-1].title }}</p>

2.4 特殊變量訪問

<p>當(dāng)前時(shí)間: {{ config.DEBUG }}</p>  <!-- 訪問Flask配置 -->
<p>請(qǐng)求方法: {{ request.method }}</p>  <!-- 訪問請(qǐng)求對(duì)象 -->
<p>會(huì)話信息: {{ session.get('user_id') }}</p>
<p>閃現(xiàn)消息: {{ get_flashed_messages() }}</p>

三、過濾器的使用

3.1 內(nèi)置過濾器大全

Jinja2提供了豐富的內(nèi)置過濾器:

<!-- 字符串處理 -->
<p>{{ "hello"|capitalize }}</p>  <!-- Hello -->
<p>{{ "HELLO"|lower }}</p>  <!-- hello -->
<p>{{ "hello world"|title }}</p>  <!-- Hello World -->
<p>{{ "hello"|replace("e", "a") }}</p>  <!-- hallo -->

<!-- 列表處理 -->
<p>{{ [1,2,3]|length }}</p>  <!-- 3 -->
<p>{{ [1,2,3]|first }}</p>  <!-- 1 -->
<p>{{ [1,2,3]|last }}</p>  <!-- 3 -->
<p>{{ [1,2,3]|join("|") }}</p>  <!-- 1|2|3 -->

<!-- 數(shù)值處理 -->
<p>{{ 3.1415926|round(2) }}</p>  <!-- 3.14 -->
<p>{{ 1000|filesizeformat }}</p>  <!-- 1000 Bytes -->
<p>{{ 0.85|float }}</p>  <!-- 0.85 -->

<!-- 日期處理 -->
<p>{{ user.create_time|datetimeformat }}</p>
<p>{{ user.create_time|datetimeformat('%Y-%m-%d') }}</p>

<!-- HTML處理 -->
<p>{{ "<script>alert(1)</script>"|escape }}</p>
<p>{{ "Markdown text"|markdown }}</p>
<p>{{ "https://example.com"|urlencode }}</p>

3.2 自定義過濾器

在app.py中注冊(cè)自定義過濾器:

@app.template_filter('reverse')
def reverse_filter(s):
    return s[::-1]

@app.template_filter('format_phone')
def format_phone(phone):
    return f"{phone[:3]}-{phone[3:7]}-{phone[7:]}"

模板中使用:

<p>{{ "hello"|reverse }}</p>  <!-- olleh -->
<p>{{ "13812345678"|format_phone }}</p>  <!-- 138-1234-5678 -->

Flask模板高級(jí)技巧

1.控制語句

條件判斷

{% if user.age < 18 %}
    <p>未成年用戶</p>
{% elif user.age > 60 %}
    <p>老年用戶</p>
{% else %}
    <p>成年用戶</p>
{% endif %}

循環(huán)語句

<table>
    <thead>
        <tr>
            <th>序號(hào)</th>
            <th>標(biāo)題</th>
            <th>內(nèi)容</th>
        </tr>
    </thead>
    <tbody>
        {% for post in posts %}
        <tr class="{{ loop.cycle('odd', 'even') }}">
            <td>{{ loop.index }}</td>
            <td>{{ post.title }}</td>
            <td>{{ post.content }}</td>
        </tr>
        {% else %}
        <tr>
            <td colspan="3">暫無文章</td>
        </tr>
        {% endfor %}
    </tbody>
</table>

循環(huán)變量說明:

  • loop.index: 當(dāng)前迭代次數(shù)(從1開始)
  • loop.index0: 當(dāng)前迭代次數(shù)(從0開始)
  • loop.revindex: 反向迭代次數(shù)
  • loop.first: 是否第一次迭代
  • loop.last: 是否最后一次迭代
  • loop.length: 序列長度

宏定義(模板函數(shù))

定義宏:

{% macro render_comment(comment) %}
<div class="comment">
    <p>{{ comment.author }} 說:</p>
    <blockquote>{{ comment.content }}</blockquote>
</div>
{% endmacro %}

使用宏:

{{ render_comment(comment) }}

<!-- 導(dǎo)入其他模板中的宏 -->
{% from 'macros.html' import render_comment %}

2.模板繼承

基礎(chǔ)模板(base.html)

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}默認(rèn)標(biāo)題{% endblock %}</title>
    {% block head %}
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" rel="external nofollow" >
    {% endblock %}
</head>
<body>
    <div class="container">
        {% block content %}
        <h1>默認(rèn)內(nèi)容</h1>
        {% endblock %}
    </div>
    
    {% block footer %}
    <footer>
        <p>&copy; 2023 My App</p>
    </footer>
    {% endblock %}
</body>
</html>

子模板繼承

{% extends "base.html" %}

{% block title %}用戶主頁 - {{ super() }}{% endblock %}

{% block head %}
    {{ super() }}
    <style>
        .profile { color: blue; }
    </style>
{% endblock %}

{% block content %}
    <div class="profile">
        <h1>{{ user.username }}的個(gè)人資料</h1>
        <p>年齡: {{ user.age }}</p>
    </div>
{% endblock %}

{% block footer %}
    <footer>
        <p>&copy; 2023 用戶中心</p>
    </footer>
{% endblock %}

包含其他模板

<!-- 包含頭部 -->
{% include 'header.html' %}

<!-- 帶參數(shù)包含 -->
{% include 'user_card.html' with user=current_user %}

<!-- 忽略缺失模板 -->
{% include 'sidebar.html' ignore missing %}

3.加載靜態(tài)文件

靜態(tài)文件組織

標(biāo)準(zhǔn)項(xiàng)目結(jié)構(gòu):

myapp/
├── app.py
├── static/
│   ├── css/
│   ├── js/
│   └── images/
└── templates/

引用靜態(tài)文件

<!-- CSS文件 -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}" rel="external nofollow" >

<!-- JavaScript文件 -->
<script src="{{ url_for('static', filename='js/main.js') }}"></script>

<!-- 圖片 -->
<img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo">

<!-- 使用緩存清除 -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css', v=1.0) }}" rel="external nofollow" >

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

在配置中添加版本號(hào):

app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600  # 1小時(shí)緩存
app.config['STATIC_VERSION'] = '1.0.0'

模板中使用:

<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}?v={{ config.STATIC_VERSION }}" rel="external nofollow" >

使用CDN資源

{% if config.CDN_ENABLED %}
    <script src="https://cdn.example.com/jquery/3.6.0.min.js"></script>
{% else %}
    <script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>
{% endif %}

以上就是Python中Flask模板的使用與高級(jí)技巧詳解的詳細(xì)內(nèi)容,更多關(guān)于Python Flask模板的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

江西省| 方山县| 新安县| 土默特右旗| 宜州市| 大名县| 天台县| 建湖县| 托克托县| 蛟河市| 栖霞市| 瑞安市| 吴江市| 来安县| 绍兴市| 客服| 九龙县| 简阳市| 通化市| 宁强县| 巩义市| 河曲县| 麻江县| 大庆市| 定结县| 洛宁县| 奎屯市| 厦门市| 会理县| 大连市| 兴山县| 布尔津县| 南昌县| 剑阁县| 莫力| 吉安市| 武隆县| 娱乐| 沭阳县| 定陶县| 天峨县|