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

如何为Plotly Dash多页面应用的当前导航页添加active类名

解决Plotly Dash多页面应用导航链接高亮问题

要实现当前页面导航链接的高亮,核心是根据当前路径动态给对应链接添加active类名,可以通过回调动态生成导航项来实现,具体步骤如下:

1. 修改导航容器结构

给导航的外层容器设置唯一id,方便回调定位更新:

html.Div(
  id="nav-items",
  className="items",
),

2. 编写回调动态生成导航链接

通过监听url组件的pathname,动态生成每个导航链接,并判断当前路径是否匹配页面路径,匹配则添加active类:

@app.callback(
    Output("nav-items", "children"),
    Input("url", "pathname")
)
def update_nav(pathname):
    nav_items = []
    for page in dash.page_registry.values():
        # 匹配当前路径与页面路径,一致则添加active类
        link_class = "active" if pathname == page["relative_path"] else ""
        nav_items.append(
            html.Div(
                dcc.Link(
                    page["name"],
                    href=page["relative_path"],
                    className=link_class
                )
            )
        )
    return nav_items

3. 定义active类的高亮样式

在你的CSS文件(或app.css)中添加active类的样式,比如:

.active {
    color: #119dff; /* 高亮文字颜色 */
    font-weight: bold;
    border-bottom: 2px solid #119dff; /* 底部下划线高亮 */
}

处理嵌套路径的情况

如果你的应用有嵌套路径(比如/docs和/docs/install),可以用startswith来匹配父路径,让父导航也保持高亮:

link_class = "active" if pathname.startswith(page["relative_path"]) else ""

这样当你切换页面时,回调会自动更新对应导航链接的类名,实现高亮效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:35:29