pypi-streamlit

Description
A faster way to build and share data apps
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/pypi-streamlit@1.50.0

navigation-pages.md docs/

1
# Navigation and Pages
2
3
Multi-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.
4
5
## Capabilities
6
7
### Page Configuration
8
9
Configure page-level settings and metadata for your Streamlit application.
10
11
```python { .api }
12
def set_page_config(page_title=None, page_icon=None, layout="centered", initial_sidebar_state="auto", menu_items=None):
13
"""
14
Configure page settings and metadata. Must be called at the very beginning of the script.
15
16
Args:
17
page_title (str, optional): Page title shown in browser tab
18
page_icon (str, optional): Page icon (emoji or URL) shown in browser tab
19
layout (str): Page layout ("centered" or "wide")
20
initial_sidebar_state (str): Initial sidebar state ("auto", "expanded", "collapsed")
21
menu_items (dict, optional): Custom menu items configuration
22
23
Note:
24
Must be the first Streamlit command in your script
25
"""
26
```
27
28
Example usage:
29
```python
30
st.set_page_config(
31
page_title="My Dashboard",
32
page_icon="πŸ“Š",
33
layout="wide",
34
initial_sidebar_state="expanded",
35
menu_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
```
42
43
### Multi-Page Navigation
44
45
Create and manage multi-page applications with structured navigation.
46
47
```python { .api }
48
def navigation(pages, *, position="sidebar", expanded=True):
49
"""
50
Define application navigation structure with multiple pages.
51
52
Args:
53
pages (list): List of Page objects or page configurations
54
position (str): Navigation position ("sidebar" or "hidden")
55
expanded (bool): Whether navigation starts expanded
56
57
Returns:
58
Page: Currently selected page object
59
"""
60
61
class Page:
62
"""
63
Represents a single page in a multi-page application.
64
65
Args:
66
page (str or callable): Page file path or function
67
title (str, optional): Page title for navigation
68
icon (str, optional): Page icon (emoji or material icon name)
69
url_path (str, optional): Custom URL path for the page
70
default (bool): Whether this is the default page
71
"""
72
73
def __init__(self, page, *, title=None, icon=None, url_path=None, default=False):
74
pass
75
```
76
77
Example usage:
78
```python
79
# Define pages
80
home_page = st.Page("pages/home.py", title="Home", icon="🏠", default=True)
81
data_page = st.Page("pages/data.py", title="Data Analysis", icon="πŸ“Š")
82
settings_page = st.Page("pages/settings.py", title="Settings", icon="βš™οΈ")
83
84
# Create navigation
85
pg = st.navigation([home_page, data_page, settings_page])
86
87
# Run the selected page
88
pg.run()
89
90
# Advanced navigation with sections
91
pg = st.navigation({
92
"Main": [
93
st.Page("home.py", title="Dashboard", icon="πŸ“ˆ"),
94
st.Page("reports.py", title="Reports", icon="πŸ“‹")
95
],
96
"Admin": [
97
st.Page("users.py", title="User Management", icon="πŸ‘₯"),
98
st.Page("settings.py", title="System Settings", icon="βš™οΈ")
99
]
100
})
101
```
102
103
### App Logo and Branding
104
105
Configure application logo and branding elements.
106
107
```python { .api }
108
def logo(image, *, link=None, icon_image=None):
109
"""
110
Set the application logo displayed in the navigation area.
111
112
Args:
113
image (str or bytes): Logo image file path, URL, or image data
114
link (str, optional): URL to navigate when logo is clicked
115
icon_image (str or bytes, optional): Smaller icon version for mobile/compact view
116
"""
117
```
118
119
Example usage:
120
```python
121
# Set logo with link
122
st.logo("assets/company_logo.png", link="https://company.com")
123
124
# Logo with separate icon
125
st.logo(
126
image="assets/logo_full.png",
127
icon_image="assets/logo_icon.png",
128
link="https://company.com"
129
)
130
```
131
132
### Page Navigation Control
133
134
Functions for programmatically controlling page navigation and routing.
135
136
```python { .api }
137
def switch_page(page):
138
"""
139
Navigate to a different page programmatically.
140
141
Args:
142
page (str or Page): Page name, file path, or Page object to navigate to
143
"""
144
```
145
146
Example usage:
147
```python
148
# Navigate based on user action
149
if st.button("Go to Data Analysis"):
150
st.switch_page("pages/data.py")
151
152
# Navigate based on conditions
153
if not user_authenticated:
154
st.switch_page("pages/login.py")
155
156
# Navigate with Page object
157
if st.button("Go to Settings"):
158
st.switch_page(settings_page)
159
160
# Conditional navigation
161
user_role = get_user_role()
162
if user_role == "admin":
163
st.switch_page("pages/admin.py")
164
elif user_role == "user":
165
st.switch_page("pages/dashboard.py")
166
```
167
168
### Execution Control
169
170
Control the execution flow of your Streamlit application.
171
172
```python { .api }
173
def rerun():
174
"""
175
Immediately rerun the current script from the top.
176
177
Useful for refreshing the app state or triggering updates.
178
"""
179
180
def stop():
181
"""
182
Stop execution of the current script.
183
184
Nothing after this command will be executed in the current run.
185
"""
186
```
187
188
Example usage:
189
```python
190
# Rerun after data update
191
if st.button("Refresh Data"):
192
update_data()
193
st.rerun()
194
195
# Stop execution based on condition
196
if not user_has_permission:
197
st.error("Access denied")
198
st.stop()
199
200
# Conditional execution
201
if data_needs_refresh():
202
refresh_data()
203
st.rerun()
204
205
# Stop with message
206
if not config_valid:
207
st.error("Invalid configuration. Please check settings.")
208
st.stop()
209
210
# The rest of the app continues here
211
st.write("Application content...")
212
```
213
214
### Multi-Page Application Patterns
215
216
#### File-Based Pages
217
218
```python
219
# main.py - Entry point
220
import streamlit as st
221
222
# Page configuration
223
st.set_page_config(
224
page_title="Analytics Platform",
225
page_icon="πŸ“Š",
226
layout="wide"
227
)
228
229
# Define pages
230
pages = [
231
st.Page("pages/dashboard.py", title="Dashboard", icon="πŸ“ˆ", default=True),
232
st.Page("pages/data_upload.py", title="Data Upload", icon="πŸ“€"),
233
st.Page("pages/analysis.py", title="Analysis", icon="πŸ”"),
234
st.Page("pages/reports.py", title="Reports", icon="πŸ“‹"),
235
st.Page("pages/settings.py", title="Settings", icon="βš™οΈ")
236
]
237
238
# Navigation
239
pg = st.navigation(pages)
240
pg.run()
241
```
242
243
#### Function-Based Pages
244
245
```python
246
def home_page():
247
st.title("Welcome to My App")
248
st.write("This is the home page")
249
250
if st.button("Go to Data"):
251
st.switch_page(data_page)
252
253
def data_page():
254
st.title("Data Analysis")
255
st.write("Analyze your data here")
256
257
# Data analysis code
258
if st.button("Generate Report"):
259
st.switch_page(report_page)
260
261
def report_page():
262
st.title("Reports")
263
st.write("View generated reports")
264
265
# Create pages
266
home = st.Page(home_page, title="Home", icon="🏠")
267
data = st.Page(data_page, title="Data", icon="πŸ“Š")
268
report = st.Page(report_page, title="Reports", icon="πŸ“‹")
269
270
# Navigation
271
pg = st.navigation([home, data, report])
272
pg.run()
273
```
274
275
#### Conditional Navigation
276
277
```python
278
# Authentication-based navigation
279
def get_navigation():
280
if not st.session_state.get("authenticated", False):
281
return st.navigation([
282
st.Page("login.py", title="Login", icon="πŸ”")
283
])
284
285
user_role = st.session_state.get("user_role", "user")
286
287
if user_role == "admin":
288
return st.navigation({
289
"Main": [
290
st.Page("dashboard.py", title="Dashboard", icon="πŸ“Š"),
291
st.Page("analytics.py", title="Analytics", icon="πŸ“ˆ")
292
],
293
"Admin": [
294
st.Page("users.py", title="User Management", icon="πŸ‘₯"),
295
st.Page("system.py", title="System Settings", icon="βš™οΈ")
296
]
297
})
298
else:
299
return st.navigation([
300
st.Page("dashboard.py", title="Dashboard", icon="πŸ“Š"),
301
st.Page("profile.py", title="My Profile", icon="πŸ‘€")
302
])
303
304
# Use conditional navigation
305
pg = get_navigation()
306
pg.run()
307
```
308
309
#### URL-Based Routing
310
311
```python
312
# Custom URL routing with query parameters
313
def handle_routing():
314
# Get page from URL
315
page = st.query_params.get("page", "home")
316
317
# Route to appropriate function
318
if page == "home":
319
show_home()
320
elif page == "data":
321
show_data_page()
322
elif page == "settings":
323
show_settings()
324
else:
325
show_404()
326
327
def navigate_to(page_name):
328
"""Navigate to page and update URL."""
329
st.query_params["page"] = page_name
330
st.rerun()
331
332
# Navigation menu
333
col1, col2, col3 = st.columns(3)
334
with col1:
335
if st.button("Home"):
336
navigate_to("home")
337
with col2:
338
if st.button("Data"):
339
navigate_to("data")
340
with col3:
341
if st.button("Settings"):
342
navigate_to("settings")
343
344
# Handle the routing
345
handle_routing()
346
```
347
348
#### State-Aware Navigation
349
350
```python
351
# Navigation that responds to application state
352
def get_current_page():
353
# Determine page based on app state
354
if "current_workflow" not in st.session_state:
355
return "welcome"
356
357
workflow_state = st.session_state.current_workflow
358
359
if workflow_state == "data_loaded":
360
return "analysis"
361
elif workflow_state == "analysis_complete":
362
return "results"
363
else:
364
return "data_upload"
365
366
def update_workflow_state(new_state):
367
"""Update workflow state and navigate."""
368
st.session_state.current_workflow = new_state
369
st.rerun()
370
371
# State-based page display
372
current_page = get_current_page()
373
374
if current_page == "welcome":
375
st.title("Welcome")
376
if st.button("Start Analysis"):
377
update_workflow_state("ready")
378
379
elif current_page == "data_upload":
380
st.title("Upload Data")
381
uploaded_file = st.file_uploader("Choose file")
382
if uploaded_file and st.button("Process"):
383
# Process file
384
update_workflow_state("data_loaded")
385
386
elif current_page == "analysis":
387
st.title("Analysis")
388
if st.button("Run Analysis"):
389
# Run analysis
390
update_workflow_state("analysis_complete")
391
392
elif current_page == "results":
393
st.title("Results")
394
st.write("Analysis complete!")
395
```
396
397
#### Navigation with Session State
398
399
```python
400
# Initialize navigation state
401
if "nav_history" not in st.session_state:
402
st.session_state.nav_history = ["home"]
403
st.session_state.current_page = "home"
404
405
def navigate_with_history(page):
406
"""Navigate to page and maintain history."""
407
st.session_state.nav_history.append(page)
408
st.session_state.current_page = page
409
st.rerun()
410
411
def go_back():
412
"""Navigate back to previous page."""
413
if len(st.session_state.nav_history) > 1:
414
st.session_state.nav_history.pop()
415
st.session_state.current_page = st.session_state.nav_history[-1]
416
st.rerun()
417
418
# Navigation controls
419
col1, col2 = st.columns([1, 4])
420
with col1:
421
if len(st.session_state.nav_history) > 1:
422
if st.button("← Back"):
423
go_back()
424
425
# Page content based on current page
426
current_page = st.session_state.current_page
427
428
if current_page == "home":
429
st.title("Home")
430
if st.button("Go to Settings"):
431
navigate_with_history("settings")
432
433
elif current_page == "settings":
434
st.title("Settings")
435
if st.button("Go to Profile"):
436
navigate_with_history("profile")
437
```