multi-page dash app
multi-page dash app
create a '/pages' subfolder
create an individual .py file for each page in the subfolder
In every page, add the below line to register the page
dash.register_page(__name__)
In every page, define a variable 'layout' to specify the page content
create an app.py file in the main folder
declare in the app.py that it will use multiple pages
app = Dash(__name__, use_pages=True)
the app.py has its own layout, something like a frame to enclose the sub pages.
make sure add page_container to the app.py layout for displaying the sub pages.
dash.page_container
Below is an example structure of a multi-page dash app
- app.py
- pages
|-- analytics.py
|-- home.py
|-- archive.py
The app.py is the home page with a frame.
The actual pages home, archive and analytics are sub pages embedded within the frame.
by default the app.py shows the home.py.
This is the app.py. The entry point of the app.
The dcc.Link provides a link to each sub page.
The dash.page_container displays the sub page selected through the link.
from dash import Dash, html, dcc
import dash
app = Dash(__name__, use_pages=True)
app.layout = html.Div([
html.H1('Multi-page app with Dash Pages'),
html.Div(
[
html.Div(
dcc.Link(
f"{page['name']} - {page['path']}", href=page["relative_path"]
)
)
for page in dash.page_registry.values()
]
),
dash.page_container
])
if __name__ == '__main__':
app.run_server(debug=True)
The following are the subpages.
The home.py page is registerd as root path '/'. If no root path is registered, the dash.page_container doesn't know what to show when first visited, so 404 not found.
import dash
from dash import html, dcc
dash.register_page(__name__, path='/')
layout = html.Div(children=[
html.H1(children='This is our Home page'),
html.Div(children='''
This is our Home page content.
'''),
])
Nothing special about the archive.py
import dash
from dash import html, dcc
dash.register_page(__name__)
layout = html.Div(children=[
html.H1(children='This is our Archive page'),
html.Div(children='''
This is our Archive page content.
'''),
])
The analytics.py page has a callback
import dash
from dash import html, dcc, callback, Input, Output
dash.register_page(__name__)
layout = html.Div(children=[
html.H1(children='This is our Analytics page'),
html.Div([
"Select a city: ",
dcc.RadioItems(['New York City', 'Montreal','San Francisco'],
'Montreal',
id='analytics-input')
]),
html.Br(),
html.Div(id='analytics-output'),
])
@callback(
Output(component_id='analytics-output', component_property='children'),
Input(component_id='analytics-input', component_property='value')
)
def update_city_selected(input_value):
return f'You selected: {input_value}'