or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

application-routing.mdauthentication.mdcss-styling.mddevelopment-tools.mdform-handling.mdhtml-components.mdhtmx-integration.mdindex.mdjavascript-integration.mdnotifications.mdsvg-components.md

html-components.mddocs/

0

# HTML Components and Elements

1

2

Complete HTML element generation system with Python functions for every HTML tag, enhanced components with HTMX integration, and form handling capabilities.

3

4

## Capabilities

5

6

### HTML Element Functions

7

8

Every HTML element is available as a Python function with the same name. Elements accept content as positional arguments and attributes as keyword arguments.

9

10

```python { .api }

11

def A(*c, **kw):

12

"""Create HTML anchor (a) element."""

13

14

def Abbr(*c, **kw):

15

"""Create HTML abbr element."""

16

17

def Address(*c, **kw):

18

"""Create HTML address element."""

19

20

def Area(*c, **kw):

21

"""Create HTML area element."""

22

23

def Article(*c, **kw):

24

"""Create HTML article element."""

25

26

def Aside(*c, **kw):

27

"""Create HTML aside element."""

28

29

def Audio(*c, **kw):

30

"""Create HTML audio element."""

31

32

def B(*c, **kw):

33

"""Create HTML b (bold) element."""

34

35

def Base(*c, **kw):

36

"""Create HTML base element."""

37

38

def Bdi(*c, **kw):

39

"""Create HTML bdi element."""

40

41

def Bdo(*c, **kw):

42

"""Create HTML bdo element."""

43

44

def Blockquote(*c, **kw):

45

"""Create HTML blockquote element."""

46

47

def Body(*c, **kw):

48

"""Create HTML body element."""

49

50

def Br(*c, **kw):

51

"""Create HTML br (line break) element."""

52

53

def Button(*c, **kw):

54

"""Create HTML button element."""

55

56

def Canvas(*c, **kw):

57

"""Create HTML canvas element."""

58

59

def Caption(*c, **kw):

60

"""Create HTML caption element."""

61

62

def Cite(*c, **kw):

63

"""Create HTML cite element."""

64

65

def Code(*c, **kw):

66

"""Create HTML code element."""

67

68

def Col(*c, **kw):

69

"""Create HTML col element."""

70

71

def Colgroup(*c, **kw):

72

"""Create HTML colgroup element."""

73

74

def Data(*c, **kw):

75

"""Create HTML data element."""

76

77

def Datalist(*c, **kw):

78

"""Create HTML datalist element."""

79

80

def Dd(*c, **kw):

81

"""Create HTML dd element."""

82

83

def Del(*c, **kw):

84

"""Create HTML del element."""

85

86

def Details(*c, **kw):

87

"""Create HTML details element."""

88

89

def Dfn(*c, **kw):

90

"""Create HTML dfn element."""

91

92

def Dialog(*c, **kw):

93

"""Create HTML dialog element."""

94

95

def Div(*c, **kw):

96

"""Create HTML div element."""

97

98

def Dl(*c, **kw):

99

"""Create HTML dl element."""

100

101

def Dt(*c, **kw):

102

"""Create HTML dt element."""

103

104

def Em(*c, **kw):

105

"""Create HTML em (emphasis) element."""

106

107

def Embed(*c, **kw):

108

"""Create HTML embed element."""

109

110

def Fieldset(*c, **kw):

111

"""Create HTML fieldset element."""

112

113

def Figcaption(*c, **kw):

114

"""Create HTML figcaption element."""

115

116

def Figure(*c, **kw):

117

"""Create HTML figure element."""

118

119

def Footer(*c, **kw):

120

"""Create HTML footer element."""

121

122

def Form(*c, **kw):

123

"""Create HTML form element."""

124

125

def H1(*c, **kw):

126

"""Create HTML h1 heading element."""

127

128

def H2(*c, **kw):

129

"""Create HTML h2 heading element."""

130

131

def H3(*c, **kw):

132

"""Create HTML h3 heading element."""

133

134

def H4(*c, **kw):

135

"""Create HTML h4 heading element."""

136

137

def H5(*c, **kw):

138

"""Create HTML h5 heading element."""

139

140

def H6(*c, **kw):

141

"""Create HTML h6 heading element."""

142

143

def Head(*c, **kw):

144

"""Create HTML head element."""

145

146

def Header(*c, **kw):

147

"""Create HTML header element."""

148

149

def Hgroup(*c, **kw):

150

"""Create HTML hgroup element."""

151

152

def Hr(*c, **kw):

153

"""Create HTML hr (horizontal rule) element."""

154

155

def I(*c, **kw):

156

"""Create HTML i (italic) element."""

157

158

def Iframe(*c, **kw):

159

"""Create HTML iframe element."""

160

161

def Img(*c, **kw):

162

"""Create HTML img element."""

163

164

def Input(*c, **kw):

165

"""Create HTML input element."""

166

167

def Ins(*c, **kw):

168

"""Create HTML ins element."""

169

170

def Kbd(*c, **kw):

171

"""Create HTML kbd element."""

172

173

def Label(*c, **kw):

174

"""Create HTML label element."""

175

176

def Legend(*c, **kw):

177

"""Create HTML legend element."""

178

179

def Li(*c, **kw):

180

"""Create HTML li (list item) element."""

181

182

def Link(*c, **kw):

183

"""Create HTML link element."""

184

185

def Main(*c, **kw):

186

"""Create HTML main element."""

187

188

def Map(*c, **kw):

189

"""Create HTML map element."""

190

191

def Mark(*c, **kw):

192

"""Create HTML mark element."""

193

194

def Menu(*c, **kw):

195

"""Create HTML menu element."""

196

197

def Meta(*c, **kw):

198

"""Create HTML meta element."""

199

200

def Meter(*c, **kw):

201

"""Create HTML meter element."""

202

203

def Nav(*c, **kw):

204

"""Create HTML nav element."""

205

206

def Noscript(*c, **kw):

207

"""Create HTML noscript element."""

208

209

def Object(*c, **kw):

210

"""Create HTML object element."""

211

212

def Ol(*c, **kw):

213

"""Create HTML ol (ordered list) element."""

214

215

def Optgroup(*c, **kw):

216

"""Create HTML optgroup element."""

217

218

def Option(*c, **kw):

219

"""Create HTML option element."""

220

221

def Output(*c, **kw):

222

"""Create HTML output element."""

223

224

def P(*c, **kw):

225

"""Create HTML p (paragraph) element."""

226

227

def Picture(*c, **kw):

228

"""Create HTML picture element."""

229

230

def Pre(*c, **kw):

231

"""Create HTML pre element."""

232

233

def Progress(*c, **kw):

234

"""Create HTML progress element."""

235

236

def Q(*c, **kw):

237

"""Create HTML q (quotation) element."""

238

239

def Rp(*c, **kw):

240

"""Create HTML rp element."""

241

242

def Rt(*c, **kw):

243

"""Create HTML rt element."""

244

245

def Ruby(*c, **kw):

246

"""Create HTML ruby element."""

247

248

def S(*c, **kw):

249

"""Create HTML s (strikethrough) element."""

250

251

def Samp(*c, **kw):

252

"""Create HTML samp element."""

253

254

def Script(*c, **kw):

255

"""Create HTML script element."""

256

257

def Search(*c, **kw):

258

"""Create HTML search element."""

259

260

def Section(*c, **kw):

261

"""Create HTML section element."""

262

263

def Select(*c, **kw):

264

"""Create HTML select element."""

265

266

def Slot(*c, **kw):

267

"""Create HTML slot element."""

268

269

def Small(*c, **kw):

270

"""Create HTML small element."""

271

272

def Source(*c, **kw):

273

"""Create HTML source element."""

274

275

def Span(*c, **kw):

276

"""Create HTML span element."""

277

278

def Strong(*c, **kw):

279

"""Create HTML strong element."""

280

281

def Style(*c, **kw):

282

"""Create HTML style element."""

283

284

def Sub(*c, **kw):

285

"""Create HTML sub (subscript) element."""

286

287

def Summary(*c, **kw):

288

"""Create HTML summary element."""

289

290

def Sup(*c, **kw):

291

"""Create HTML sup (superscript) element."""

292

293

def Table(*c, **kw):

294

"""Create HTML table element."""

295

296

def Tbody(*c, **kw):

297

"""Create HTML tbody element."""

298

299

def Td(*c, **kw):

300

"""Create HTML td (table data) element."""

301

302

def Template(*c, **kw):

303

"""Create HTML template element."""

304

305

def Textarea(*c, **kw):

306

"""Create HTML textarea element."""

307

308

def Tfoot(*c, **kw):

309

"""Create HTML tfoot element."""

310

311

def Th(*c, **kw):

312

"""Create HTML th (table header) element."""

313

314

def Thead(*c, **kw):

315

"""Create HTML thead element."""

316

317

def Time(*c, **kw):

318

"""Create HTML time element."""

319

320

def Title(*c, **kw):

321

"""Create HTML title element."""

322

323

def Tr(*c, **kw):

324

"""Create HTML tr (table row) element."""

325

326

def Track(*c, **kw):

327

"""Create HTML track element."""

328

329

def U(*c, **kw):

330

"""Create HTML u (underline) element."""

331

332

def Ul(*c, **kw):

333

"""Create HTML ul (unordered list) element."""

334

335

def Var(*c, **kw):

336

"""Create HTML var element."""

337

338

def Video(*c, **kw):

339

"""Create HTML video element."""

340

341

def Wbr(*c, **kw):

342

"""Create HTML wbr element."""

343

```

344

345

### Enhanced HTML Generation

346

347

Core functions for creating HTML elements with enhanced attributes and HTMX support.

348

349

```python { .api }

350

def ft_html(tag: str, *c, **kw):

351

"""

352

Create HTML element with enhanced attributes.

353

354

Args:

355

tag: HTML tag name

356

*c: Child content (text, elements, etc.)

357

**kw: HTML attributes and FastHTML-specific options

358

359

Returns:

360

HTML element with processed attributes

361

"""

362

363

def ft_hx(tag: str, *c, **kw):

364

"""

365

Create HTML element with HTMX support.

366

367

Args:

368

tag: HTML tag name

369

*c: Child content

370

**kw: HTML attributes including HTMX attributes

371

372

Returns:

373

HTML element with HTMX functionality

374

"""

375

```

376

377

### Form Components and File Handling

378

379

Specialized components for form handling, file uploads, and data processing.

380

381

```python { .api }

382

def File(*c, **kw):

383

"""

384

Handle file uploads in forms.

385

386

Creates file input with proper encoding and handling.

387

388

Args:

389

*c: Child content (usually none for file inputs)

390

**kw: Input attributes (name, accept, multiple, etc.)

391

392

Returns:

393

File input element with upload handling

394

"""

395

396

def fill_form(form, obj):

397

"""

398

Fill form with data object.

399

400

Args:

401

form: HTML form element

402

obj: Object with data to populate form fields

403

404

Returns:

405

Form element with populated values

406

"""

407

408

def fill_dataclass(src, dest):

409

"""

410

Fill dataclass from source object.

411

412

Args:

413

src: Source object with data

414

dest: Destination dataclass to populate

415

416

Returns:

417

Populated dataclass instance

418

"""

419

420

def find_inputs(form):

421

"""

422

Find input elements in form.

423

424

Args:

425

form: HTML form element

426

427

Returns:

428

List of input elements found in form

429

"""

430

```

431

432

### Enhanced Form Components

433

434

Enhanced form input components with additional functionality and convenience features.

435

436

```python { .api }

437

def AX(txt, hx_get=None, target_id=None, hx_swap=None, href='#', **kwargs):

438

"""

439

Enhanced anchor tag with HTMX defaults and single text child.

440

441

Args:

442

txt: Link text content

443

hx_get: HTMX GET request URL

444

target_id: Target element for HTMX swap

445

hx_swap: HTMX swap strategy

446

href: Link URL (default '#')

447

**kwargs: Additional anchor attributes

448

449

Returns:

450

Enhanced anchor element with HTMX integration

451

"""

452

453

def CheckboxX(checked=False, label=None, value="1", id=None, name=None, **kwargs):

454

"""

455

Enhanced checkbox with label and improved handling.

456

457

Args:

458

checked: Whether checkbox is initially checked

459

label: Associated label text

460

value: Checkbox value when checked

461

id: Checkbox element ID

462

name: Form field name

463

**kwargs: Additional checkbox attributes

464

465

Returns:

466

Enhanced checkbox with optional label

467

"""

468

469

def Hidden(value="", id=None, **kwargs):

470

"""

471

Hidden input element for form data.

472

473

Args:

474

value: Hidden input value

475

id: Element ID

476

**kwargs: Additional input attributes

477

478

Returns:

479

Hidden input element

480

"""

481

482

def ScriptX(fname=None, src=None, code="", **kwargs):

483

"""

484

Enhanced script element with file loading and templating.

485

486

Args:

487

fname: JavaScript filename to load

488

src: External script URL

489

code: Inline JavaScript code

490

**kwargs: Additional script attributes

491

492

Returns:

493

Script element with enhanced functionality

494

"""

495

496

def StyleX(fname=None, **kwargs):

497

"""

498

Enhanced style element with file loading and CSS variable replacement.

499

500

Args:

501

fname: CSS filename to load

502

**kwargs: CSS variables for template replacement

503

504

Returns:

505

Style element with processed CSS

506

"""

507

```

508

509

### Enhanced Component Library

510

511

Pre-built enhanced components with additional functionality and styling for common web patterns.

512

513

```python { .api }

514

def Titled(title: str = "FastHTML app", *args, cls="container", **kwargs):

515

"""

516

Create complete HTML page with title and container.

517

518

Generates a complete HTML document structure with head, title,

519

and body containing the provided content in a styled container.

520

521

Args:

522

title: Page title for HTML head

523

*args: Body content elements

524

cls: CSS class for main container

525

**kwargs: Additional container attributes

526

527

Returns:

528

Complete HTML document structure

529

"""

530

531

class Fragment:

532

"""

533

Document fragment container for grouping elements.

534

535

Creates a document fragment that can contain multiple elements

536

without adding extra wrapper elements to the DOM.

537

"""

538

539

def __init__(self, *c):

540

"""Initialize fragment with child elements."""

541

542

def Socials(title, site_name, description, image, url=None, w=1200, h=630, twitter_site=None, creator=None, card='summary'):

543

"""

544

Social media meta tags for sharing.

545

546

Generates Open Graph and Twitter Card meta tags for rich social

547

media sharing previews.

548

549

Args:

550

title: Page/content title

551

site_name: Website name

552

description: Content description

553

image: Preview image URL

554

url: Canonical URL (optional)

555

w: Image width (default 1200)

556

h: Image height (default 630)

557

twitter_site: Twitter site handle

558

creator: Content creator handle

559

card: Twitter card type

560

561

Returns:

562

Collection of social media meta tags

563

"""

564

565

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):

566

"""

567

YouTube video embed with customization options.

568

569

Creates responsive YouTube video embed with privacy-enhanced mode

570

and customizable player options.

571

572

Args:

573

video_id: YouTube video ID

574

width: Player width

575

height: Player height

576

start_time: Start time in seconds

577

no_controls: Hide player controls

578

title: Iframe title for accessibility

579

cls: CSS classes

580

**kwargs: Additional iframe attributes

581

582

Returns:

583

YouTube embed iframe element

584

"""

585

586

def Favicon(light_icon, dark_icon):

587

"""

588

Favicon with light/dark mode support.

589

590

Creates favicon link elements that automatically switch

591

based on user's color scheme preference.

592

593

Args:

594

light_icon: Icon URL for light mode

595

dark_icon: Icon URL for dark mode

596

597

Returns:

598

Collection of favicon link elements

599

"""

600

```

601

602

### Display and Conversion Utilities

603

604

Functions for displaying elements and converting between formats.

605

606

```python { .api }

607

def show(ft):

608

"""

609

Display FastHTML elements (for Jupyter notebooks).

610

611

Args:

612

ft: FastHTML element to display

613

614

Returns:

615

Rendered HTML for display

616

"""

617

618

def html2ft(html_str: str):

619

"""

620

Convert HTML string to FastHTML elements.

621

622

Args:

623

html_str: HTML markup as string

624

625

Returns:

626

FastHTML element tree

627

"""

628

```

629

630

### Server-Sent Events

631

632

Components for real-time communication using server-sent events.

633

634

```python { .api }

635

def sse_message(data: str, event: str = None, id: str = None, retry: int = None):

636

"""

637

Create server-sent event message.

638

639

Args:

640

data: Message data

641

event: Event type

642

id: Message ID

643

retry: Retry interval in milliseconds

644

645

Returns:

646

Formatted SSE message

647

"""

648

649

class EventStream:

650

"""

651

Server-sent events stream handler.

652

653

Manages persistent connections for real-time updates.

654

"""

655

656

def __init__(self):

657

"""Initialize event stream."""

658

659

def send_event(self, data: str, event: str = None):

660

"""Send event to connected clients."""

661

```

662

663

### Attribute Processing

664

665

Utilities for processing and transforming HTML attributes.

666

667

```python { .api }

668

def attrmap_x(kw: dict):

669

"""

670

Map attributes with transformations.

671

672

Processes FastHTML-specific attribute names and converts

673

them to standard HTML attributes.

674

675

Args:

676

kw: Dictionary of attributes

677

678

Returns:

679

Transformed attribute dictionary

680

"""

681

682

def snake2hyphens(s: str) -> str:

683

"""

684

Convert snake_case to hyphenated format.

685

686

Args:

687

s: String in snake_case format

688

689

Returns:

690

String in hyphenated format

691

"""

692

```

693

694

## Usage Examples

695

696

### Basic HTML Structure

697

698

```python

699

from fasthtml.common import *

700

701

# Create a complete HTML page

702

page = Html(

703

Head(

704

Title("My FastHTML Page"),

705

Meta(charset="utf-8"),

706

Meta(name="viewport", content="width=device-width, initial-scale=1"),

707

Link(rel="stylesheet", href="/static/style.css")

708

),

709

Body(

710

Header(

711

Nav(

712

Ul(

713

Li(A("Home", href="/")),

714

Li(A("About", href="/about")),

715

Li(A("Contact", href="/contact"))

716

)

717

)

718

),

719

Main(

720

Section(

721

H1("Welcome to FastHTML"),

722

P("This is a paragraph with ", Strong("bold"), " and ", Em("italic"), " text."),

723

Div(

724

Button("Click me", onclick="alert('Hello!')"),

725

cls="button-container"

726

)

727

)

728

),

729

Footer(

730

P("© 2024 My FastHTML App")

731

)

732

)

733

)

734

```

735

736

### Form Creation and Handling

737

738

```python

739

from fasthtml.common import *

740

741

# Create a form with various input types

742

contact_form = Form(

743

Fieldset(

744

Legend("Contact Information"),

745

Div(

746

Label("Name:", for_="name"),

747

Input(type="text", name="name", id="name", required=True),

748

cls="form-group"

749

),

750

Div(

751

Label("Email:", for_="email"),

752

Input(type="email", name="email", id="email", required=True),

753

cls="form-group"

754

),

755

Div(

756

Label("Phone:", for_="phone"),

757

Input(type="tel", name="phone", id="phone"),

758

cls="form-group"

759

),

760

Div(

761

Label("Message:", for_="message"),

762

Textarea(name="message", id="message", rows="5", required=True),

763

cls="form-group"

764

),

765

Div(

766

Label(

767

Input(type="checkbox", name="newsletter", value="yes"),

768

" Subscribe to newsletter"

769

),

770

cls="form-group"

771

),

772

Div(

773

Button("Send Message", type="submit"),

774

cls="form-group"

775

)

776

),

777

method="post",

778

action="/contact",

779

cls="contact-form"

780

)

781

782

# Handle file uploads

783

upload_form = Form(

784

Div(

785

Label("Upload file:", for_="file"),

786

File(name="file", id="file", accept=".jpg,.png,.pdf"),

787

cls="form-group"

788

),

789

Button("Upload", type="submit"),

790

method="post",

791

action="/upload",

792

enctype="multipart/form-data"

793

)

794

```

795

796

### Dynamic Content with HTMX

797

798

```python

799

from fasthtml.common import *

800

801

# Create interactive elements with HTMX

802

interactive_content = Div(

803

H2("Dynamic Content"),

804

Button(

805

"Load Content",

806

hx_get="/api/content",

807

hx_target="#content-area",

808

hx_swap="innerHTML"

809

),

810

Div(id="content-area",

811

P("Click the button to load content dynamically")

812

),

813

814

# Form with HTMX submission

815

Form(

816

Input(type="text", name="query", placeholder="Search..."),

817

Button("Search", type="submit"),

818

hx_post="/search",

819

hx_target="#search-results",

820

hx_swap="innerHTML"

821

),

822

Div(id="search-results")

823

)

824

```

825

826

### Table Generation

827

828

```python

829

from fasthtml.common import *

830

831

# Create data table

832

data = [

833

{"name": "Alice", "age": 30, "city": "New York"},

834

{"name": "Bob", "age": 25, "city": "San Francisco"},

835

{"name": "Charlie", "age": 35, "city": "Chicago"}

836

]

837

838

table = Table(

839

Thead(

840

Tr(

841

Th("Name"),

842

Th("Age"),

843

Th("City")

844

)

845

),

846

Tbody(

847

*[Tr(

848

Td(row["name"]),

849

Td(str(row["age"])),

850

Td(row["city"])

851

) for row in data]

852

),

853

cls="data-table"

854

)

855

```

856

857

### Multimedia Elements

858

859

```python

860

from fasthtml.common import *

861

862

# Audio and video elements

863

media_content = Section(

864

H3("Multimedia Content"),

865

866

# Video with controls

867

Video(

868

Source(src="/videos/demo.mp4", type="video/mp4"),

869

Source(src="/videos/demo.webm", type="video/webm"),

870

"Your browser does not support the video tag.",

871

controls=True,

872

width="640",

873

height="360"

874

),

875

876

# Audio player

877

Audio(

878

Source(src="/audio/song.mp3", type="audio/mpeg"),

879

Source(src="/audio/song.ogg", type="audio/ogg"),

880

"Your browser does not support the audio tag.",

881

controls=True

882

),

883

884

# Image gallery

885

Div(

886

*[Figure(

887

Img(src=f"/images/gallery/{i}.jpg", alt=f"Gallery image {i}"),

888

Figcaption(f"Image {i}")

889

) for i in range(1, 6)],

890

cls="image-gallery"

891

)

892

)

893

```