【发布时间】:2021-12-24 20:28:47
【问题描述】:
我根据示例制作了一个简单的侧边栏 https://dash-bootstrap-components.opensource.faculty.ai/examples/simple-sidebar/
现在我需要在用户更改页面时更改导航栏内容。我想让它动态和分层。
这意味着我应该在页面更改时更改侧边栏布局。加载普通页面内容时这很容易,但侧边栏组件不会因页面而异。
因此我认为关键问题是如何在用户点击新页面时刷新app.layout,并且脚本分别在下面的link_list中修改(modify_test)?
这是侧边栏代码的基本部分(!不工作!):
link_list = [
dbc.NavLink("Home", href="/", active="exact"),
dbc.NavLink("Page 1", href="/page-1", active="exact"),
dbc.NavLink("Page 2", href="/page-2", active="exact"),
]
def modify_test ():
link_list.append(dbc.NavLink("Page 3", href="/page-3", active="exact"))
sidebar = html.Div(
[
html.H2("Sidebar", className="display-4"),
html.Hr(),
html.P(
"A simple sidebar layout with navigation links", className="lead"
),
dbc.Nav(
link_list,
vertical=True,
pills=True,
),
],
style=SIDEBAR_STYLE,
)
content = html.Div(id="page-content", style=CONTENT_STYLE)
app.layout = html.Div([dcc.Location(id="url"), sidebar, content])
@app.callback(Output("page-content", "children"), [Input("url", "pathname")])
def render_page_content(pathname):
if pathname == "/":
return html.P("This is the content of the home page!")
elif pathname == "/page-1":
modify_test ()
return html.P("This is the content of page 1. Yay!")
elif pathname == "/page-2":
return html.P("Oh cool, this is page 2!")
# If the user tries to reach a different page, return a 404 message
return dbc.Jumbotron(
[
html.H1("404: Not found", className="text-danger"),
html.Hr(),
html.P(f"The pathname {pathname} was not recognised..."),
]
)
【问题讨论】:
-
你能解释一下当页面改变时你想用什么方式改变侧边栏布局?在我看来,您只需在针对侧边栏的回调中添加一个额外的
Output即可处理它。 -
@BasvanderLinden 我想让它分层,所以会有曲折和下拉列表。并且列表内容也会根据用户操作而变化。我是 Dash 和 Web 客户端的新手,所以我可能会遗漏一些明显的替代方案。例如。我不知道添加额外输出是什么意思;这应该有什么帮助?
标签: plotly-dash dash-bootstrap-components