You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask项目中基于Jinja动态修改base.html侧边栏元素颜色

简洁实现Flask侧边栏当前页面高亮

核心思路

在基础模板base.html中通过Jinja条件判断,给当前页面对应的侧边栏链接添加激活样式;子模板仅需设置一个标识当前页面的变量,无需重复编写侧边栏代码。

具体实现步骤

  1. 编写base.html基础模板
    定义通用的侧边栏结构,通过current_page变量判断是否为当前页面,添加激活CSS类:

    <!DOCTYPE html>
    <html>
    <head>
        <style>
            .sidebar-link {
                color: #333; /* 默认文字颜色 */
                padding: 10px;
                display: block;
                text-decoration: none;
                margin: 5px 0;
            }
            .sidebar-link.active {
                color: #007bff; /* 选中时的高亮颜色 */
                background-color: #e9ecef; /* 可选:添加背景色增强视觉 */
                font-weight: bold;
            }
        </style>
    </head>
    <body>
        <div class="sidebar">
            <a href="{{ url_for('dashboard') }}" 
               class="sidebar-link {% if current_page == 'dashboard' %}active{% endif %}">
                Dashboard
            </a>
            <a href="{{ url_for('feature1') }}" 
               class="sidebar-link {% if current_page == 'feature1' %}active{% endif %}">
                Feature1
            </a>
            <a href="{{ url_for('feature2') }}" 
               class="sidebar-link {% if current_page == 'feature2' %}active{% endif %}">
                Feature2
            </a>
        </div>
    
        {% block content %}{% endblock %}
    </body>
    </html>
    
  2. 子模板继承并设置当前页面标识
    每个页面模板仅需继承base.html,并通过{% set %}定义current_page变量,无需重复编写侧边栏:

    • dashboard.html示例:
      {% extends "base.html" %}
      
      {% set current_page = 'dashboard' %}
      
      {% block content %}
          <h1>Dashboard 首页内容</h1>
      {% endblock %}
      
    • feature1.html示例:
      {% extends "base.html" %}
      
      {% set current_page = 'feature1' %}
      
      {% block content %}
          <h1>Feature1 功能页面内容</h1>
      {% endblock %}
      

可选优化:全局注入当前页面变量

如果不想在每个子模板中写{% set %},可以在Flask视图层全局注入current_page:

from flask import Flask, render_template, request

app = Flask(__name__)

# 上下文处理器,全局注入当前页面标识
@app.context_processor
def inject_current_page():
    return dict(current_page=request.endpoint)

@app.route('/')
def dashboard():
    return render_template('dashboard.html')

@app.route('/feature1')
def feature1():
    return render_template('feature1.html')

@app.route('/feature2')
def feature2():
    return render_template('feature2.html')

这种方式下,子模板无需设置current_page,直接利用视图函数的端点名称(如dashboard、feature1)作为判断依据,进一步简化代码。

内容的提问来源于stack exchange,提问作者Ces

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 23:42:56