The fastest way to create HTML apps - a next-generation Python web framework for building fast, scalable web applications with minimal code
—
Complete HTML element generation system with Python functions for every HTML tag, enhanced components with HTMX integration, and form handling capabilities.
Every HTML element is available as a Python function with the same name. Elements accept content as positional arguments and attributes as keyword arguments.
def A(*c, **kw):
"""Create HTML anchor (a) element."""
def Abbr(*c, **kw):
"""Create HTML abbr element."""
def Address(*c, **kw):
"""Create HTML address element."""
def Area(*c, **kw):
"""Create HTML area element."""
def Article(*c, **kw):
"""Create HTML article element."""
def Aside(*c, **kw):
"""Create HTML aside element."""
def Audio(*c, **kw):
"""Create HTML audio element."""
def B(*c, **kw):
"""Create HTML b (bold) element."""
def Base(*c, **kw):
"""Create HTML base element."""
def Bdi(*c, **kw):
"""Create HTML bdi element."""
def Bdo(*c, **kw):
"""Create HTML bdo element."""
def Blockquote(*c, **kw):
"""Create HTML blockquote element."""
def Body(*c, **kw):
"""Create HTML body element."""
def Br(*c, **kw):
"""Create HTML br (line break) element."""
def Button(*c, **kw):
"""Create HTML button element."""
def Canvas(*c, **kw):
"""Create HTML canvas element."""
def Caption(*c, **kw):
"""Create HTML caption element."""
def Cite(*c, **kw):
"""Create HTML cite element."""
def Code(*c, **kw):
"""Create HTML code element."""
def Col(*c, **kw):
"""Create HTML col element."""
def Colgroup(*c, **kw):
"""Create HTML colgroup element."""
def Data(*c, **kw):
"""Create HTML data element."""
def Datalist(*c, **kw):
"""Create HTML datalist element."""
def Dd(*c, **kw):
"""Create HTML dd element."""
def Del(*c, **kw):
"""Create HTML del element."""
def Details(*c, **kw):
"""Create HTML details element."""
def Dfn(*c, **kw):
"""Create HTML dfn element."""
def Dialog(*c, **kw):
"""Create HTML dialog element."""
def Div(*c, **kw):
"""Create HTML div element."""
def Dl(*c, **kw):
"""Create HTML dl element."""
def Dt(*c, **kw):
"""Create HTML dt element."""
def Em(*c, **kw):
"""Create HTML em (emphasis) element."""
def Embed(*c, **kw):
"""Create HTML embed element."""
def Fieldset(*c, **kw):
"""Create HTML fieldset element."""
def Figcaption(*c, **kw):
"""Create HTML figcaption element."""
def Figure(*c, **kw):
"""Create HTML figure element."""
def Footer(*c, **kw):
"""Create HTML footer element."""
def Form(*c, **kw):
"""Create HTML form element."""
def H1(*c, **kw):
"""Create HTML h1 heading element."""
def H2(*c, **kw):
"""Create HTML h2 heading element."""
def H3(*c, **kw):
"""Create HTML h3 heading element."""
def H4(*c, **kw):
"""Create HTML h4 heading element."""
def H5(*c, **kw):
"""Create HTML h5 heading element."""
def H6(*c, **kw):
"""Create HTML h6 heading element."""
def Head(*c, **kw):
"""Create HTML head element."""
def Header(*c, **kw):
"""Create HTML header element."""
def Hgroup(*c, **kw):
"""Create HTML hgroup element."""
def Hr(*c, **kw):
"""Create HTML hr (horizontal rule) element."""
def I(*c, **kw):
"""Create HTML i (italic) element."""
def Iframe(*c, **kw):
"""Create HTML iframe element."""
def Img(*c, **kw):
"""Create HTML img element."""
def Input(*c, **kw):
"""Create HTML input element."""
def Ins(*c, **kw):
"""Create HTML ins element."""
def Kbd(*c, **kw):
"""Create HTML kbd element."""
def Label(*c, **kw):
"""Create HTML label element."""
def Legend(*c, **kw):
"""Create HTML legend element."""
def Li(*c, **kw):
"""Create HTML li (list item) element."""
def Link(*c, **kw):
"""Create HTML link element."""
def Main(*c, **kw):
"""Create HTML main element."""
def Map(*c, **kw):
"""Create HTML map element."""
def Mark(*c, **kw):
"""Create HTML mark element."""
def Menu(*c, **kw):
"""Create HTML menu element."""
def Meta(*c, **kw):
"""Create HTML meta element."""
def Meter(*c, **kw):
"""Create HTML meter element."""
def Nav(*c, **kw):
"""Create HTML nav element."""
def Noscript(*c, **kw):
"""Create HTML noscript element."""
def Object(*c, **kw):
"""Create HTML object element."""
def Ol(*c, **kw):
"""Create HTML ol (ordered list) element."""
def Optgroup(*c, **kw):
"""Create HTML optgroup element."""
def Option(*c, **kw):
"""Create HTML option element."""
def Output(*c, **kw):
"""Create HTML output element."""
def P(*c, **kw):
"""Create HTML p (paragraph) element."""
def Picture(*c, **kw):
"""Create HTML picture element."""
def Pre(*c, **kw):
"""Create HTML pre element."""
def Progress(*c, **kw):
"""Create HTML progress element."""
def Q(*c, **kw):
"""Create HTML q (quotation) element."""
def Rp(*c, **kw):
"""Create HTML rp element."""
def Rt(*c, **kw):
"""Create HTML rt element."""
def Ruby(*c, **kw):
"""Create HTML ruby element."""
def S(*c, **kw):
"""Create HTML s (strikethrough) element."""
def Samp(*c, **kw):
"""Create HTML samp element."""
def Script(*c, **kw):
"""Create HTML script element."""
def Search(*c, **kw):
"""Create HTML search element."""
def Section(*c, **kw):
"""Create HTML section element."""
def Select(*c, **kw):
"""Create HTML select element."""
def Slot(*c, **kw):
"""Create HTML slot element."""
def Small(*c, **kw):
"""Create HTML small element."""
def Source(*c, **kw):
"""Create HTML source element."""
def Span(*c, **kw):
"""Create HTML span element."""
def Strong(*c, **kw):
"""Create HTML strong element."""
def Style(*c, **kw):
"""Create HTML style element."""
def Sub(*c, **kw):
"""Create HTML sub (subscript) element."""
def Summary(*c, **kw):
"""Create HTML summary element."""
def Sup(*c, **kw):
"""Create HTML sup (superscript) element."""
def Table(*c, **kw):
"""Create HTML table element."""
def Tbody(*c, **kw):
"""Create HTML tbody element."""
def Td(*c, **kw):
"""Create HTML td (table data) element."""
def Template(*c, **kw):
"""Create HTML template element."""
def Textarea(*c, **kw):
"""Create HTML textarea element."""
def Tfoot(*c, **kw):
"""Create HTML tfoot element."""
def Th(*c, **kw):
"""Create HTML th (table header) element."""
def Thead(*c, **kw):
"""Create HTML thead element."""
def Time(*c, **kw):
"""Create HTML time element."""
def Title(*c, **kw):
"""Create HTML title element."""
def Tr(*c, **kw):
"""Create HTML tr (table row) element."""
def Track(*c, **kw):
"""Create HTML track element."""
def U(*c, **kw):
"""Create HTML u (underline) element."""
def Ul(*c, **kw):
"""Create HTML ul (unordered list) element."""
def Var(*c, **kw):
"""Create HTML var element."""
def Video(*c, **kw):
"""Create HTML video element."""
def Wbr(*c, **kw):
"""Create HTML wbr element."""Core functions for creating HTML elements with enhanced attributes and HTMX support.
def ft_html(tag: str, *c, **kw):
"""
Create HTML element with enhanced attributes.
Args:
tag: HTML tag name
*c: Child content (text, elements, etc.)
**kw: HTML attributes and FastHTML-specific options
Returns:
HTML element with processed attributes
"""
def ft_hx(tag: str, *c, **kw):
"""
Create HTML element with HTMX support.
Args:
tag: HTML tag name
*c: Child content
**kw: HTML attributes including HTMX attributes
Returns:
HTML element with HTMX functionality
"""Specialized components for form handling, file uploads, and data processing.
def File(*c, **kw):
"""
Handle file uploads in forms.
Creates file input with proper encoding and handling.
Args:
*c: Child content (usually none for file inputs)
**kw: Input attributes (name, accept, multiple, etc.)
Returns:
File input element with upload handling
"""
def fill_form(form, obj):
"""
Fill form with data object.
Args:
form: HTML form element
obj: Object with data to populate form fields
Returns:
Form element with populated values
"""
def fill_dataclass(src, dest):
"""
Fill dataclass from source object.
Args:
src: Source object with data
dest: Destination dataclass to populate
Returns:
Populated dataclass instance
"""
def find_inputs(form):
"""
Find input elements in form.
Args:
form: HTML form element
Returns:
List of input elements found in form
"""Enhanced form input components with additional functionality and convenience features.
def AX(txt, hx_get=None, target_id=None, hx_swap=None, href='#', **kwargs):
"""
Enhanced anchor tag with HTMX defaults and single text child.
Args:
txt: Link text content
hx_get: HTMX GET request URL
target_id: Target element for HTMX swap
hx_swap: HTMX swap strategy
href: Link URL (default '#')
**kwargs: Additional anchor attributes
Returns:
Enhanced anchor element with HTMX integration
"""
def CheckboxX(checked=False, label=None, value="1", id=None, name=None, **kwargs):
"""
Enhanced checkbox with label and improved handling.
Args:
checked: Whether checkbox is initially checked
label: Associated label text
value: Checkbox value when checked
id: Checkbox element ID
name: Form field name
**kwargs: Additional checkbox attributes
Returns:
Enhanced checkbox with optional label
"""
def Hidden(value="", id=None, **kwargs):
"""
Hidden input element for form data.
Args:
value: Hidden input value
id: Element ID
**kwargs: Additional input attributes
Returns:
Hidden input element
"""
def ScriptX(fname=None, src=None, code="", **kwargs):
"""
Enhanced script element with file loading and templating.
Args:
fname: JavaScript filename to load
src: External script URL
code: Inline JavaScript code
**kwargs: Additional script attributes
Returns:
Script element with enhanced functionality
"""
def StyleX(fname=None, **kwargs):
"""
Enhanced style element with file loading and CSS variable replacement.
Args:
fname: CSS filename to load
**kwargs: CSS variables for template replacement
Returns:
Style element with processed CSS
"""Pre-built enhanced components with additional functionality and styling for common web patterns.
def Titled(title: str = "FastHTML app", *args, cls="container", **kwargs):
"""
Create complete HTML page with title and container.
Generates a complete HTML document structure with head, title,
and body containing the provided content in a styled container.
Args:
title: Page title for HTML head
*args: Body content elements
cls: CSS class for main container
**kwargs: Additional container attributes
Returns:
Complete HTML document structure
"""
class Fragment:
"""
Document fragment container for grouping elements.
Creates a document fragment that can contain multiple elements
without adding extra wrapper elements to the DOM.
"""
def __init__(self, *c):
"""Initialize fragment with child elements."""
def Socials(title, site_name, description, image, url=None, w=1200, h=630, twitter_site=None, creator=None, card='summary'):
"""
Social media meta tags for sharing.
Generates Open Graph and Twitter Card meta tags for rich social
media sharing previews.
Args:
title: Page/content title
site_name: Website name
description: Content description
image: Preview image URL
url: Canonical URL (optional)
w: Image width (default 1200)
h: Image height (default 630)
twitter_site: Twitter site handle
creator: Content creator handle
card: Twitter card type
Returns:
Collection of social media meta tags
"""
def YouTubeEmbed(video_id: str, width: int = 560, height: int = 315, start_time: int = 0, no_controls: bool = False, title: str = "YouTube video player", cls: str = "", **kwargs):
"""
YouTube video embed with customization options.
Creates responsive YouTube video embed with privacy-enhanced mode
and customizable player options.
Args:
video_id: YouTube video ID
width: Player width
height: Player height
start_time: Start time in seconds
no_controls: Hide player controls
title: Iframe title for accessibility
cls: CSS classes
**kwargs: Additional iframe attributes
Returns:
YouTube embed iframe element
"""
def Favicon(light_icon, dark_icon):
"""
Favicon with light/dark mode support.
Creates favicon link elements that automatically switch
based on user's color scheme preference.
Args:
light_icon: Icon URL for light mode
dark_icon: Icon URL for dark mode
Returns:
Collection of favicon link elements
"""Functions for displaying elements and converting between formats.
def show(ft):
"""
Display FastHTML elements (for Jupyter notebooks).
Args:
ft: FastHTML element to display
Returns:
Rendered HTML for display
"""
def html2ft(html_str: str):
"""
Convert HTML string to FastHTML elements.
Args:
html_str: HTML markup as string
Returns:
FastHTML element tree
"""Components for real-time communication using server-sent events.
def sse_message(data: str, event: str = None, id: str = None, retry: int = None):
"""
Create server-sent event message.
Args:
data: Message data
event: Event type
id: Message ID
retry: Retry interval in milliseconds
Returns:
Formatted SSE message
"""
class EventStream:
"""
Server-sent events stream handler.
Manages persistent connections for real-time updates.
"""
def __init__(self):
"""Initialize event stream."""
def send_event(self, data: str, event: str = None):
"""Send event to connected clients."""Utilities for processing and transforming HTML attributes.
def attrmap_x(kw: dict):
"""
Map attributes with transformations.
Processes FastHTML-specific attribute names and converts
them to standard HTML attributes.
Args:
kw: Dictionary of attributes
Returns:
Transformed attribute dictionary
"""
def snake2hyphens(s: str) -> str:
"""
Convert snake_case to hyphenated format.
Args:
s: String in snake_case format
Returns:
String in hyphenated format
"""from fasthtml.common import *
# Create a complete HTML page
page = Html(
Head(
Title("My FastHTML Page"),
Meta(charset="utf-8"),
Meta(name="viewport", content="width=device-width, initial-scale=1"),
Link(rel="stylesheet", href="/static/style.css")
),
Body(
Header(
Nav(
Ul(
Li(A("Home", href="/")),
Li(A("About", href="/about")),
Li(A("Contact", href="/contact"))
)
)
),
Main(
Section(
H1("Welcome to FastHTML"),
P("This is a paragraph with ", Strong("bold"), " and ", Em("italic"), " text."),
Div(
Button("Click me", onclick="alert('Hello!')"),
cls="button-container"
)
)
),
Footer(
P("© 2024 My FastHTML App")
)
)
)from fasthtml.common import *
# Create a form with various input types
contact_form = Form(
Fieldset(
Legend("Contact Information"),
Div(
Label("Name:", for_="name"),
Input(type="text", name="name", id="name", required=True),
cls="form-group"
),
Div(
Label("Email:", for_="email"),
Input(type="email", name="email", id="email", required=True),
cls="form-group"
),
Div(
Label("Phone:", for_="phone"),
Input(type="tel", name="phone", id="phone"),
cls="form-group"
),
Div(
Label("Message:", for_="message"),
Textarea(name="message", id="message", rows="5", required=True),
cls="form-group"
),
Div(
Label(
Input(type="checkbox", name="newsletter", value="yes"),
" Subscribe to newsletter"
),
cls="form-group"
),
Div(
Button("Send Message", type="submit"),
cls="form-group"
)
),
method="post",
action="/contact",
cls="contact-form"
)
# Handle file uploads
upload_form = Form(
Div(
Label("Upload file:", for_="file"),
File(name="file", id="file", accept=".jpg,.png,.pdf"),
cls="form-group"
),
Button("Upload", type="submit"),
method="post",
action="/upload",
enctype="multipart/form-data"
)from fasthtml.common import *
# Create interactive elements with HTMX
interactive_content = Div(
H2("Dynamic Content"),
Button(
"Load Content",
hx_get="/api/content",
hx_target="#content-area",
hx_swap="innerHTML"
),
Div(id="content-area",
P("Click the button to load content dynamically")
),
# Form with HTMX submission
Form(
Input(type="text", name="query", placeholder="Search..."),
Button("Search", type="submit"),
hx_post="/search",
hx_target="#search-results",
hx_swap="innerHTML"
),
Div(id="search-results")
)from fasthtml.common import *
# Create data table
data = [
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "San Francisco"},
{"name": "Charlie", "age": 35, "city": "Chicago"}
]
table = Table(
Thead(
Tr(
Th("Name"),
Th("Age"),
Th("City")
)
),
Tbody(
*[Tr(
Td(row["name"]),
Td(str(row["age"])),
Td(row["city"])
) for row in data]
),
cls="data-table"
)from fasthtml.common import *
# Audio and video elements
media_content = Section(
H3("Multimedia Content"),
# Video with controls
Video(
Source(src="/videos/demo.mp4", type="video/mp4"),
Source(src="/videos/demo.webm", type="video/webm"),
"Your browser does not support the video tag.",
controls=True,
width="640",
height="360"
),
# Audio player
Audio(
Source(src="/audio/song.mp3", type="audio/mpeg"),
Source(src="/audio/song.ogg", type="audio/ogg"),
"Your browser does not support the audio tag.",
controls=True
),
# Image gallery
Div(
*[Figure(
Img(src=f"/images/gallery/{i}.jpg", alt=f"Gallery image {i}"),
Figcaption(f"Image {i}")
) for i in range(1, 6)],
cls="image-gallery"
)
)Install with Tessl CLI
npx tessl i tessl/pypi-python-fasthtml