
Faststrap: Component-based FastHTML extension that provides reusable UI elements
Python-native UI components for FastHTML apps, dashboards, data tools, and AI-ready interfaces.
以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。
Python-native UI components for FastHTML apps, dashboards, data tools, and AI-ready interfaces.
FastStrap helps Python developers build production web apps, admin panels, analytics dashboards, modelling tools, and agent-friendly interfaces with FastHTML, Bootstrap 5, and HTMX. The core stays lightweight and dependency-conscious: write Python, get polished HTML, and add JavaScript only when an optional integration truly needs it.
FastHTML is amazing for building web apps in pure Python, but complete product and data interfaces still need a reliable UI layer. FastStrap fills that gap by providing:
It also ships higher-level modules for HTMX presets, SEO metadata composition, and PWA setup so production concerns are covered alongside UI components. The roadmap keeps heavier capabilities, such as richer plotting, ML dashboards, and agent surfaces, as focused optional integrations rather than bloating the core.
Installation
pip install faststrap
Optional renderers can be installed only when you need them:
pip install "faststrap[markdown]"
faststrap[markdown] installs the Python packages used by the Markdown display component. Chart.js and GSAP integrations load browser assets through add_chartjs(app) and add_gsap(app) and do not add Python dependencies.
from fasthtml.common import FastHTML, serve from faststrap import add_bootstrap, Card, Button, create_theme
app = FastHTML()
Use built-in theme or create custom
theme = create_theme(primary="#7BA05B", secondary="#48C774") add_bootstrap(app, theme=theme, mode="dark")
@app.route("/") def home(): return Card( "Welcome to FastStrap! Build beautiful UIs in pure Python.", header="Hello World!", footer=Button("Get Started", variant="primary") )
serve()
That's it! You now have a modern, responsive web app with zero JavaScript.
Faststrap V0.5.1+ includes a helper to easily mount your own static files (images, CSS, etc.):
from faststrap import mount_assets
Mount your "assets" directory at "/assets" URL
mount_assets(app, "assets")
Use in your app
Img(src="/assets/logo.png") Div(style="background-image: url('/assets/hero.jpg')")
See Static Files Guide for more details.
Explore, test props, and preview all 73 FastStrap components interactively on your local machine with zero network latency — no cloud server costs, no cold starts, no internet required:
pip install faststrap-preview-studio faststrap-preview
Opens a local studio at http://localhost:8080 with:
The Studio bundles all FastStrap stylesheets and Bootstrap JS locally, so it works fully offline after installation.
- Enhanced Attribute Handling
Faststrap now supports advanced attribute handling:
from faststrap import Button
Style dict and CSS variables
Button( "Styled Button", style={"background-color": "#7BA05B", "border": "none"}, css_vars={"--bs-btn-padding-y": "0.75rem", "--bs-btn-border-radius": "12px"}, data={"id": "123", "type": "demo"}, aria={"label": "Styled button"}, )
Filter None/False values automatically
Button("Test", disabled=None, hidden=False) # None/False values are dropped
- CloseButton Helper
Reusable close button for alerts, modals, and drawers:
from faststrap import CloseButton, Alert
Use in alerts
Alert( "This alert uses CloseButton helper", variant="info", dismissible=True, )
Use in modals/drawers (automatically used)
- Expanded Button Component
More control over button appearance and behavior:
from faststrap import Button
Render as link
Button("As Link", as_="a", href="/page", variant="secondary")
Loading states with custom text
Button("Loading", loading=True, loading_text="Please wait...", spinner=True)
Full width, pill, active states
Button("Full Width", full_width=True, variant="info") Button("Pill", pill=True, variant="warning") Button("Active", active=True, variant="success")
Icon and loading spinner control
Button("Save", icon="check-circle", icon_pos="start") Button("Saving", loading=True, spinner=True, loading_text="Saving...")
- Slot Class Overrides
Fine-grained control over component parts:
from faststrap import Card, Modal, Drawer, Dropdown
Card with custom slot classes
Card( "Content", header="Custom Header", footer="Custom Footer", header_cls="bg-primary text-white p-3", body_cls="p-4", footer_cls="text-muted", )
Modal with custom classes
Modal( "Modal content", title="Custom Modal", dialog_cls="shadow-lg", content_cls="border-0", header_cls="bg-primary text-white", body_cls="p-4", )
Drawer with custom classes
Drawer( "Drawer content", title="Custom Drawer", header_cls="bg-success text-white", body_cls="p-4", )
Dropdown with custom classes
Dropdown( "Option 1", "Option 2", label="Custom Dropdown", toggle_cls="custom-toggle", menu_cls="custom-menu", item_cls="custom-item", )
- Theme System
Create and apply custom themes:
from faststrap import create_theme, add_bootstrap
Create custom theme
my_theme = create_theme( primary="#7BA05B", secondary="#48C774", info="#36A3EB", warning="#FFC107", danger="#DC3545", success="#28A745", light="#F8F9FA", dark="#343A40", )
Use built-in themes
add_bootstrap(app, theme="green-nature") # or "blue-ocean", "purple-magic", etc.
Or use custom theme
add_bootstrap(app, theme=my_theme)
Available built-in themes:
Components include metadata about category, stability, and JavaScript requirements. The registry also helps developers and AI agents discover existing components before inventing new wrappers:
from faststrap import ( find_components, get_component, get_components_by_pattern, list_component_metadata, list_components, )
components = list_components(category="display") cards = find_components("card") toast_components = get_components_by_pattern("toast") metadata = list_component_metadata()
Check if component requires JS
modal = get_component("Modal")
Modal is registered with requires_js=True
Available Components And Helpers
Faststrap currently exposes 179 registered UI components across forms, display, feedback, navigation, layout, and patterns, plus 22 HTMX preset helpers, SEO/PWA helpers, accessibility helpers, core utilities, and optional integrations. Components are typed, HTMX-friendly, and follow Bootstrap conventions. Stability markers (@stable, @beta, @experimental) indicate API maturity.
ActiveSearch
InfiniteScroll
AutoRefresh
LazyLoad
LoadingButton
OptimisticAction
LocationAction
PollUntil
ConfirmPrompt
Debounce
SwapOnEvent
hx_redirect
hx_refresh
hx_trigger
hx_reswap
hx_retarget
toast_response
SSEStream
sse_event
sse_comment
@require_auth
Forms (36 Public Components / Helpers)
Button
ButtonGroup
ButtonToolbar
CalendarDatePicker
Checkbox
CloseButton
DateRangePicker
ExportButton
FileInput
FilterBar
FloatingActionButton
FloatingLabel
Form
FormBuilder
FormErrorSummary
FormGroup
FormGroupFromErrors
FormSection
FormWizard
GradientButton
Input
InputGroup
InputGroupText
InlineEditor
LiveValidationField
MultiSelect
Radio
Range
RangeSlider
SearchableSelect
Select
Switch
ThemeToggle
ToggleGroup
ValidationMessage
WizardStep
Display (42 Components + 5 table aliases)
Avatar
AvatarGroup
Badge
BadgeGroup
Card
Carousel
CarouselItem
Chart
CodeBlock
DataTable
EmptyState
Figure
FlipCard
GlowCard
Image
JsonViewer
KPICard
KeyValueList
MapView
Markdown
Mermaid
MetricCard
RecordDetail
ResultCard
RevealCard
Sheet
SSETarget
StatCard
StatusBadge
Stepper
StepperStep
Svg
BsTable / BsTHead / BsTBody / BsTRow / BsTCell
Table
THead
TBody
TRow
TCell
TextClamp
Timeline
TimelineItem
TiltCard
TrendCard
v0.6.1 Naming Notes
FormBuilder is now the preferred name for the Pydantic form builder API. If you are on v0.6.0 or earlier, keep using Form.from_pydantic(). In v0.6.1+, prefer FormBuilder.from_pydantic(). Form remains as a compatibility alias.
Table, THead, TBody, TRow, and TCell remain the primary table API. v0.6.1 adds optional aliases BsTable, BsTHead, BsTBody, BsTRow, and BsTCell for projects that import both FastHTML and Faststrap table primitives.
Feedback (35 Components)
Alert
ConfirmAction
ConfirmDialog
DotsLoader
ErrorDialog
ErrorPage
ErrorToast
InfoToast
InstallPrompt
Modal
ModernToast
ModernToastStack
NoticeAlert
NoticeToast
NotificationCenter
Placeholder
PlaceholderButton
PlaceholderCard
PolygonLoader
Popover
Progress
ProgressBar
ProgressRing
PulseLoader
RingLoader
ShadowLoader
SimpleToast
Spinner
SuccessToast
Toast
ToastContainer
Tooltip
TypewriterLoader
WarningToast
WaveLoader
Navigation (23 Components)
Accordion
AccordionItem
BottomNav
BottomNavItem
Breadcrumb
Collapse
CommandItem
CommandPalette
Drawer
Dropdown
DropdownDivider
DropdownItem
GlassNavbar
GlassNavItem
ListGroup
ListGroupItem
Navbar
Pagination
Scrollspy
SidebarNavbar
SidebarNavItem
TabPane
Tabs
Layout (10 Components)
Container
Row
Col
Stack
Cluster
Center
Hero
DashboardGrid
PageHeader
ParallaxSection
Patterns (8 Composed Components)
Feature
FeatureGrid
FooterModern
NavbarModern
PricingGroup
PricingTier
Testimonial
TestimonialSection
Layouts (3 Composed Layouts)
DashboardLayout
LandingLayout
AuthLayout
Accessibility (4 Helpers)
SkipLink
LiveRegion
VisuallyHidden
FocusTrap
Effects (1 Module)
Fx - Zero-JS animations and visual effects
Optional Integrations (3 Opt-In Systems)
ChartJS - Optional Chart.js integration via add_chartjs(app)
Gsap / Motion / GsapReveal - Optional GSAP motion integration via add_gsap(app)
ModernToast - Opinionated modern toast surface that remains separate from the core Bootstrap toast API
Core Discovery And Theme Utilities
list_components
get_component
find_components
get_components_by_pattern
list_component_metadata
theme_variant_css
Documentation Coverage
Docs are actively being expanded to match the full API surface. See the docs site and examples/ for current coverage and usage patterns.
View docs: https://faststrap-org.github.io/Faststrap/
Faststrap has a dedicated showcase/ layer for polished, product-style references. These are fuller applications and landing pages, not tiny component demos.
See the full gallery in the Showcase docs.
Comprehensive examples organized by learning path:
hello_world.py - Your first Faststrap app
first_card.py - Working with components
simple_form.py - Building forms
adding_htmx.py - HTMX interactivity
03_real_world_apps/
blog/ - Complete blog with posts, comments, admin
calculator/ - HTMX-powered calculator
game/ - Tic-tac-toe with win detection
ecommerce/ - E-commerce store (existing)
04_advanced/
effects_showcase.py - All Faststrap effects demo
custom_themes.py - Theme customization
component_defaults.py - Global configuration
05_new_components/
v070_component_wave.py - Core v0.7.0 component wave demo
v070_workflow_patterns.py - HTMX workflow and helper patterns
v070_optional_integrations.py - ModernToast, ChartJS, and GSAP opt-in integrations
See: examples/README.md for complete guide
The latest tagged release is v0.9.1. The current source tree includes any follow-up work recorded under [Unreleased] in CHANGELOG.md.
For the current source of truth on future build direction, see ROADMAP.md.
- Adding Bootstrap to Your App
from fasthtml.common import FastHTML from faststrap import add_bootstrap, create_theme
app = FastHTML()
Basic setup (includes default FastStrap favicon)
add_bootstrap(app)
With dark mode
add_bootstrap(app, mode="dark")
Custom theme
theme = create_theme(primary="#7BA05B", secondary="#48C774") add_bootstrap(app, theme=theme)
Using CDN
Note: this covers Faststrap-managed assets only.
Your own app CSS/images still need to be served by your deployment setup.
add_bootstrap(app, use_cdn=True)
- Using Components
All components follow Bootstrap's conventions with Pythonic names:
from faststrap import Button, Badge, Alert, Input, Select, Tabs
Button with HTMX
Button("Save", variant="primary",
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。