I have 1 Location Component on my inde File, which loads the layout depending on the URL. I want to have a callback that has the Location component as the output and, different Inputs from all the other Files that include different Layouts. It doesnt work tho, cause ofc only the active Layouts Input ist actually currently available while the others are not loaded. How i can work around that?
Each layout that you load in can also have a dcc.Location
. If you set refresh=True
in that, you can output things to it and it will set the URL as your output and go to that location.
Example:
app.layout = html.Div([
dcc.Location(id='main-url',refresh=False),
html.Div(id='page-content'),
])
layout2 = html.Div([
dcc.Location(id='page-url',refresh=True)
])
@app.callback(
Output('page-content','children'),
Input('main-url','pathname')
)
def router(...):
if something:
return page_layout
...
@app.callback(
Output('page-url','pathname'),
[Input('mydiv','some_property')]
)
def this_will_refresh_the_page(...):
...
return url
Thx, man. The first 5 minutes i was confused on how this could help my case, but it totally did. Just a small thing though, is there a way to achieve this without having the page reload? Its not detrimental, just QoL. Thanks a lot again. Cheers!
Glad it helped. The refresh is necessary; otherwise the URL changes but the page content stays the same.
This is a functioning example - copy and run to see.
import dash_html_components as html
import dash_core_components as dcc
import dash
from dash.dependencies import Output, Input
app = dash.Dash(__name__)
app.config.suppress_callback_exceptions = True
app.layout = html.Div([
dcc.Location(id='main-url',refresh=False),
dcc.Link('home',href='/'),html.Br(),
dcc.Link('page',href='/page'),html.Br(),
dcc.Link('nonrefresh',href='/nonrefresh'),html.Br(),
html.Div(id='page-content'),
])
page_layout = html.Div([
dcc.Location(id='page-url',refresh=True),
html.Button('this changes the URL and takes you home because it refreshes',id='page-button',n_clicks=0)
])
nonrefresh_layout = html.Div([
dcc.Location(id='nonrefresh-url',refresh=False),
html.Button('this changes the URL and does not take you to home because it does not refresh',id='nonrefresh-button',n_clicks=0)
])
@app.callback(
Output('page-content','children'),
[Input('main-url','pathname')])
def router(pathname):
if pathname=='/':
return 'home'
elif pathname=='/page':
return page_layout
elif pathname=='/nonrefresh':
return nonrefresh_layout
return '404'
@app.callback(
Output('page-url','pathname'),
[Input('page-button','n_clicks')])
def this_will_go_home(n_clicks):
if n_clicks>0:
return '/'
@app.callback(
Output('nonrefresh-url','pathname'),
[Input('nonrefresh-button','n_clicks')])
def this_wont_go_home(n_clicks):
if n_clicks>0:
return '/'
if __name__ == "__main__":
app.run_server(debug=True)