- Spec files
pypi-streamlit
Describes: pkg:pypi/streamlit@1.50.x
- Description
- A faster way to build and share data apps
- Author
- tessl
- Last updated
navigation-pages.md docs/
1# Navigation and Pages23Multi-page application support, navigation controls, and execution flow management. Streamlit provides comprehensive tools for building sophisticated multi-page applications with navigation, routing, and execution control.45## Capabilities67### Page Configuration89Configure page-level settings and metadata for your Streamlit application.1011```python { .api }12def set_page_config(page_title=None, page_icon=None, layout="centered", initial_sidebar_state="auto", menu_items=None):13"""14Configure page settings and metadata. Must be called at the very beginning of the script.1516Args:17page_title (str, optional): Page title shown in browser tab18page_icon (str, optional): Page icon (emoji or URL) shown in browser tab19layout (str): Page layout ("centered" or "wide")20initial_sidebar_state (str): Initial sidebar state ("auto", "expanded", "collapsed")21menu_items (dict, optional): Custom menu items configuration2223Note:24Must be the first Streamlit command in your script25"""26```2728Example usage:29```python30st.set_page_config(31page_title="My Dashboard",32page_icon="π",33layout="wide",34initial_sidebar_state="expanded",35menu_items={36"About": "This is my awesome dashboard!",37"Report a bug": "mailto:support@example.com",38"Get help": "https://docs.streamlit.io"39}40)41```4243### Multi-Page Navigation4445Create and manage multi-page applications with structured navigation.4647```python { .api }48def navigation(pages, *, position="sidebar", expanded=True):49"""50Define application navigation structure with multiple pages.5152Args:53pages (list): List of Page objects or page configurations54position (str): Navigation position ("sidebar" or "hidden")55expanded (bool): Whether navigation starts expanded5657Returns:58Page: Currently selected page object59"""6061class Page:62"""63Represents a single page in a multi-page application.6465Args:66page (str or callable): Page file path or function67title (str, optional): Page title for navigation68icon (str, optional): Page icon (emoji or material icon name)69url_path (str, optional): Custom URL path for the page70default (bool): Whether this is the default page71"""7273def __init__(self, page, *, title=None, icon=None, url_path=None, default=False):74pass75```7677Example usage:78```python79# Define pages80home_page = st.Page("pages/home.py", title="Home", icon="π ", default=True)81data_page = st.Page("pages/data.py", title="Data Analysis", icon="π")82settings_page = st.Page("pages/settings.py", title="Settings", icon="βοΈ")8384# Create navigation85pg = st.navigation([home_page, data_page, settings_page])8687# Run the selected page88pg.run()8990# Advanced navigation with sections91pg = st.navigation({92"Main": [93st.Page("home.py", title="Dashboard", icon="π"),94st.Page("reports.py", title="Reports", icon="π")95],96"Admin": [97st.Page("users.py", title="User Management", icon="π₯"),98st.Page("settings.py", title="System Settings", icon="βοΈ")99]100})101```102103### App Logo and Branding104105Configure application logo and branding elements.106107```python { .api }108def logo(image, *, link=None, icon_image=None):109"""110Set the application logo displayed in the navigation area.111112Args:113image (str or bytes): Logo image file path, URL, or image data114link (str, optional): URL to navigate when logo is clicked115icon_image (str or bytes, optional): Smaller icon version for mobile/compact view116"""117```118119Example usage:120```python121# Set logo with link122st.logo("assets/company_logo.png", link="https://company.com")123124# Logo with separate icon125st.logo(126image="assets/logo_full.png",127icon_image="assets/logo_icon.png",128link="https://company.com"129)130```131132### Page Navigation Control133134Functions for programmatically controlling page navigation and routing.135136```python { .api }137def switch_page(page):138"""139Navigate to a different page programmatically.140141Args:142page (str or Page): Page name, file path, or Page object to navigate to143"""144```145146Example usage:147```python148# Navigate based on user action149if st.button("Go to Data Analysis"):150st.switch_page("pages/data.py")151152# Navigate based on conditions153if not user_authenticated:154st.switch_page("pages/login.py")155156# Navigate with Page object157if st.button("Go to Settings"):158st.switch_page(settings_page)159160# Conditional navigation161user_role = get_user_role()162if user_role == "admin":163st.switch_page("pages/admin.py")164elif user_role == "user":165st.switch_page("pages/dashboard.py")166```167168### Execution Control169170Control the execution flow of your Streamlit application.171172```python { .api }173def rerun():174"""175Immediately rerun the current script from the top.176177Useful for refreshing the app state or triggering updates.178"""179180def stop():181"""182Stop execution of the current script.183184Nothing after this command will be executed in the current run.185"""186```187188Example usage:189```python190# Rerun after data update191if st.button("Refresh Data"):192update_data()193st.rerun()194195# Stop execution based on condition196if not user_has_permission:197st.error("Access denied")198st.stop()199200# Conditional execution201if data_needs_refresh():202refresh_data()203st.rerun()204205# Stop with message206if not config_valid:207st.error("Invalid configuration. Please check settings.")208st.stop()209210# The rest of the app continues here211st.write("Application content...")212```213214### Multi-Page Application Patterns215216#### File-Based Pages217218```python219# main.py - Entry point220import streamlit as st221222# Page configuration223st.set_page_config(224page_title="Analytics Platform",225page_icon="π",226layout="wide"227)228229# Define pages230pages = [231st.Page("pages/dashboard.py", title="Dashboard", icon="π", default=True),232st.Page("pages/data_upload.py", title="Data Upload", icon="π€"),233st.Page("pages/analysis.py", title="Analysis", icon="π"),234st.Page("pages/reports.py", title="Reports", icon="π"),235st.Page("pages/settings.py", title="Settings", icon="βοΈ")236]237238# Navigation239pg = st.navigation(pages)240pg.run()241```242243#### Function-Based Pages244245```python246def home_page():247st.title("Welcome to My App")248st.write("This is the home page")249250if st.button("Go to Data"):251st.switch_page(data_page)252253def data_page():254st.title("Data Analysis")255st.write("Analyze your data here")256257# Data analysis code258if st.button("Generate Report"):259st.switch_page(report_page)260261def report_page():262st.title("Reports")263st.write("View generated reports")264265# Create pages266home = st.Page(home_page, title="Home", icon="π ")267data = st.Page(data_page, title="Data", icon="π")268report = st.Page(report_page, title="Reports", icon="π")269270# Navigation271pg = st.navigation([home, data, report])272pg.run()273```274275#### Conditional Navigation276277```python278# Authentication-based navigation279def get_navigation():280if not st.session_state.get("authenticated", False):281return st.navigation([282st.Page("login.py", title="Login", icon="π")283])284285user_role = st.session_state.get("user_role", "user")286287if user_role == "admin":288return st.navigation({289"Main": [290st.Page("dashboard.py", title="Dashboard", icon="π"),291st.Page("analytics.py", title="Analytics", icon="π")292],293"Admin": [294st.Page("users.py", title="User Management", icon="π₯"),295st.Page("system.py", title="System Settings", icon="βοΈ")296]297})298else:299return st.navigation([300st.Page("dashboard.py", title="Dashboard", icon="π"),301st.Page("profile.py", title="My Profile", icon="π€")302])303304# Use conditional navigation305pg = get_navigation()306pg.run()307```308309#### URL-Based Routing310311```python312# Custom URL routing with query parameters313def handle_routing():314# Get page from URL315page = st.query_params.get("page", "home")316317# Route to appropriate function318if page == "home":319show_home()320elif page == "data":321show_data_page()322elif page == "settings":323show_settings()324else:325show_404()326327def navigate_to(page_name):328"""Navigate to page and update URL."""329st.query_params["page"] = page_name330st.rerun()331332# Navigation menu333col1, col2, col3 = st.columns(3)334with col1:335if st.button("Home"):336navigate_to("home")337with col2:338if st.button("Data"):339navigate_to("data")340with col3:341if st.button("Settings"):342navigate_to("settings")343344# Handle the routing345handle_routing()346```347348#### State-Aware Navigation349350```python351# Navigation that responds to application state352def get_current_page():353# Determine page based on app state354if "current_workflow" not in st.session_state:355return "welcome"356357workflow_state = st.session_state.current_workflow358359if workflow_state == "data_loaded":360return "analysis"361elif workflow_state == "analysis_complete":362return "results"363else:364return "data_upload"365366def update_workflow_state(new_state):367"""Update workflow state and navigate."""368st.session_state.current_workflow = new_state369st.rerun()370371# State-based page display372current_page = get_current_page()373374if current_page == "welcome":375st.title("Welcome")376if st.button("Start Analysis"):377update_workflow_state("ready")378379elif current_page == "data_upload":380st.title("Upload Data")381uploaded_file = st.file_uploader("Choose file")382if uploaded_file and st.button("Process"):383# Process file384update_workflow_state("data_loaded")385386elif current_page == "analysis":387st.title("Analysis")388if st.button("Run Analysis"):389# Run analysis390update_workflow_state("analysis_complete")391392elif current_page == "results":393st.title("Results")394st.write("Analysis complete!")395```396397#### Navigation with Session State398399```python400# Initialize navigation state401if "nav_history" not in st.session_state:402st.session_state.nav_history = ["home"]403st.session_state.current_page = "home"404405def navigate_with_history(page):406"""Navigate to page and maintain history."""407st.session_state.nav_history.append(page)408st.session_state.current_page = page409st.rerun()410411def go_back():412"""Navigate back to previous page."""413if len(st.session_state.nav_history) > 1:414st.session_state.nav_history.pop()415st.session_state.current_page = st.session_state.nav_history[-1]416st.rerun()417418# Navigation controls419col1, col2 = st.columns([1, 4])420with col1:421if len(st.session_state.nav_history) > 1:422if st.button("β Back"):423go_back()424425# Page content based on current page426current_page = st.session_state.current_page427428if current_page == "home":429st.title("Home")430if st.button("Go to Settings"):431navigate_with_history("settings")432433elif current_page == "settings":434st.title("Settings")435if st.button("Go to Profile"):436navigate_with_history("profile")437```