Python code for navigation with submenus in the sidebar for a multi page app
- User
Python code for navigation with submenus in the sidebar for a multi page app
- Assistant
Python code for navigation with submenus in the sidebar for a multi page app
Certainly! Below is an example of how you can create a multi-page Python web application with a sidebar that includes navigation with submenus. This example uses the Dash framework along with Dash Bootstrap Components to create a responsive and interactive web app.
First, make sure you have Dash and Dash Bootstrap Components installed:
pip install dash
pip install dash-bootstrap-components
Here's the complete code:
import dash
from dash import html, dcc, Input, Output, State
import dash_bootstrap_components as dbc
# Initialize the Dash app with a Bootstrap stylesheet
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
# Dictionary to define the submenu structure
submenu_pages = {
'Data Management': [
{'label': 'Upload Data', 'value': '/upload-data'},
{'label': 'View Data', 'value': '/view-data'},
],
'Analysis': [
{'label': 'Statistics', 'value': '/statistics'},
{'label': 'Visualization', 'value': '/visualization'},
],
'Settings': [
{'label': 'Profile', 'value': '/profile'},
{'label': 'Preferences', 'value': '/preferences'},
]
}
def create_sidebar():
# Generate the sidebar content dynamically
menu = []
for submenu_title, pages in submenu_pages.items():
# Create the submenu header
submenu_header = dbc.NavLink(
[
html.Span(submenu_title),
html.Span(className="navbar-toggler-icon", style={'float': 'right'}),
],
href="#",
id=f"submenu-header-{submenu_title}",
n_clicks=0,
className="submenu-header",
)
# Create the submenu collapse
submenu_collapse = dbc.Collapse(
dbc.Nav(
[
dbc.NavLink(
page['label'],
href=page['value'],
id=f"page-link-{page['value']}",
className="submenu-item",
)
for page in pages
],
vertical=True,
pills=True,
),
id=f"submenu-collapse-{submenu_title}",
is_open=False,
)
# Add the header and collapse to the menu
menu.extend([submenu_header, submenu_collapse])
sidebar = html.Div(
[
html.H2('My App', className='display-4'),
html.Hr(),
dbc.Nav(
menu,
vertical=True,
pills=True,
className="bg-light",
),
],
style={
'position': 'fixed',
'top': 0,
'left': 0,
'bottom': 0,
'width': '16rem',
'padding': '2rem 1rem',
'background-color': '#f8f9fa',
'overflowY': 'auto',
},
)
return sidebar
# Define the main layout
app.layout = html.Div(
[
dcc.Location(id='url'),
create_sidebar(),
html.Div(id='page-content', style={'margin-left': '18rem', 'padding': '2rem 1rem'}),
]
)
# Callback to toggle submenus
for submenu_title in submenu_pages.keys():
app.callback(
Output(f"submenu-collapse-{submenu_title}", "is_open"),
[Input(f"submenu-header-{submenu_title}", "n_clicks")],
[State(f"submenu-collapse-{submenu_title}", "is_open")],
)(
# Define the function separately to avoid closures
lambda n, is_open: not is_open if n else is_open
)
# Callback to update the page content
@app.callback(Output('page-content', 'children'), [Input('url', 'pathname')])
def display_page(pathname):
if pathname == '/upload-data':
return html.H3('Upload Data Page')
elif pathname == '/view-data':
return html.H3('View Data Page')
elif pathname == '/statistics':
return html.H3('Statistics Page')
elif pathname == '/visualization':
return html.H3('Visualization Page')
elif pathname == '/profile':
return html.H3('Profile Page')
elif pathname == '/preferences':
return html.H3('Preferences Page')
else:
return html.H3('Welcome to the App')
if __name__ == '__main__':
app.run_server(debug=True)
Explanation of the Code:
Imports:
dash and dash_bootstrap_components are imported to build the app and style it using Bootstrap components.Initializing the App:
Defining Submenus:
submenu_pages dictionary defines the submenu titles and their respective pages.Creating the Sidebar:
create_sidebar function dynamically creates the sidebar with submenus and links.submenu_header) and collapsible content (submenu_collapse) containing the page links.Main Layout:
dcc.Location) for URL routing, the sidebar, and a content area where the pages will be displayed.Callbacks:
page-content div based on the current URL pathname.Styling and Customization:
Styling the Sidebar:
overflowY property ensures that the sidebar is scrollable if the content overflows.Adding Icons and Additional Styles:
html.Span elements within submenu_header to include icons or indicators.Running the App:
Save the code to a file, for example, app.py.
Run the app using the command:
python app.py
Open http://127.0.0.1:8050/ in your web browser to view the app.
Additional Notes:
Page Content:
display_page function, you can replace the html.H3 placeholders with the actual content or layouts of your pages.Extending the App:
submenu_pages dictionary.href values in the page links match the pathname checks in the display_page callback.URL Routing:
dcc.Location component for client-side routing. The pathname reflects the URL path, enabling back/forward navigation in the browser.Conclusion:
This example demonstrates how to create a navigable sidebar with submenus in a Dash web application. By leveraging Dash's callbacks and Bootstrap components, you can build interactive and responsive web apps entirely in Python.
Feel free to customize and expand upon this template to suit your application's needs!