Skip to content

DataTable

DataTable is a higher-level table with sorting, search, and pagination built in. It accepts list[dict] and pandas or polars DataFrames.

Beta API

DataTable is currently marked @beta. It is stable enough for real apps, but query contracts and helper ergonomics may still evolve in minor releases.


Quick Start

Live Preview
Name Email Status
Ada Lovelace ada@example.com Active
Alan Turing alan@example.com Invited
from faststrap import DataTable

DataTable(
    data,
    sortable=True,
    searchable=True,
    pagination=True,
    per_page=25,
    endpoint="/users",
)

Data Sources

DataTable accepts:

  • list[dict]
  • pandas DataFrame
  • polars DataFrame
DataTable(
    records,
    columns=["name", "email", "status"],
    header_map={"name": "User", "email": "Email"},
    include_index=False,
)

Enable sorting and search with flags. For interactive controls, provide endpoint or base_url so header links and search submits have a stable request target:

DataTable(
    data,
    sortable=True,
    searchable=True,
    search_placeholder="Search users...",
    search_param="q",
    search_debounce=300,
    endpoint="/users",
)

Restrict sortable columns with a list:

DataTable(data, sortable=["name", "email"])

If you want to control the current state (server-side mode), pass sort, direction, and search.


Pagination

Client-side pagination works for small sets when you render the full dataset locally. For server-side pagination, pass total_rows with endpoint or base_url.

DataTable(
    data,
    pagination=True,
    page=2,
    per_page=50,
    total_rows=1200,
)

Mobile Card Presentation

The default mobile_mode="scroll" preserves the existing semantic table and responsive horizontal-scrolling behavior. This is often best for analytics and data-science work where comparing columns matters. For a narrow-screen record browsing layout, choose mobile_mode="cards" or mobile_mode="stack".

Faststrap renders the semantic table at and above the selected breakpoint and the requested card/stack presentation below it. Both representations use the same current filtered, sorted, paginated records and wrapper ID. Sort, search, pagination, and polling continue targeting the same wrapper; no custom JavaScript is required. The table representation remains in the response so server-rendered state and responsive resizing stay synchronized.

In local mode (no endpoint or base_url), Faststrap filters/sorts and slices the in-memory records before rendering both views. In endpoint mode, your route must query and pass the current page's rows; total_rows supplies the global count for pagination. Both responsive presentations then render that same server-provided page.

DataTable(
    files,
    columns=["name", "owner", "size", "updated_at", "internal_id"],
    header_map={
        "name": "File",
        "owner": "Owner",
        "size": "Size",
        "updated_at": "Updated",
    },
    searchable=True,
    pagination=True,
    endpoint="/files",
    mobile_mode="cards",
    mobile_breakpoint="lg",
    mobile_title="name",
    mobile_subtitle="owner",
    mobile_meta=["size", "updated_at"],
    mobile_hidden=["internal_id"],
    mobile_card_cls="shadow-sm",
)

Modes And Field Selection

mobile_mode Small-screen output
"scroll" (default) Only the semantic table, using the existing responsive behavior.
None Only the semantic table; the responsive option still controls horizontal overflow. Use this to explicitly disable an alternate mobile presentation.
"cards" A responsive grid of individually surfaced record cards.
"stack" A vertical sequence of flatter record rows.

mobile_breakpoint accepts Bootstrap breakpoints sm, md, lg, xl, and xxl. The table appears at and above that breakpoint; mobile content appears below it. mobile_title defaults to the first data column. mobile_subtitle is optional. If mobile_meta is omitted, remaining columns become labeled metadata; pass an explicit list to choose order, or [] to omit metadata. mobile_hidden removes columns from generated mobile output only; the desktop table is unaffected. Labels come from header_map when available, otherwise the column key is shown.

Unknown names in mobile_title, mobile_subtitle, mobile_meta, mobile_hidden, or mobile_field_renderers raise ValueError rather than being silently ignored.

Custom Field Rendering

Use mobile_field_renderers to format values or return composed FastHTML elements while retaining Faststrap's generated title/metadata layout:

from faststrap import DataTable, StatusBadge

DataTable(
    experiments,
    columns=["name", "status", "accuracy"],
    header_map={"accuracy": "Accuracy"},
    mobile_mode="cards",
    mobile_title="name",
    mobile_meta=["status", "accuracy"],
    mobile_field_renderers={
        "status": lambda value, row: StatusBadge(str(value).title(), status=value),
        "accuracy": lambda value, row: f"{value:.1%}",
    },
)

Each field renderer receives (value, row), where row is the normalized row dictionary. Return text or FastHTML content. Field renderers apply only to metadata fields, not the title or subtitle slots.

Custom Mobile Cards And Actions

For a different card structure or row-specific actions, provide mobile_card_renderer. It receives one normalized row dictionary and returns FastHTML content. The result is wrapped in Faststrap's record surface and receives mobile_card_cls and mobile_card_attrs:

from fasthtml.common import Div
from faststrap import Button, DataTable, StatusBadge

DataTable(
    jobs,
    columns=["id", "name", "status", "owner"],
    mobile_mode="cards",
    mobile_card_cls="p-3",
    mobile_card_attrs={"data-testid": "job-card"},
    mobile_card_renderer=lambda row: Div(
        Div(row["name"], cls="fw-semibold"),
        StatusBadge(str(row["status"]).title(), status=row["status"]),
        Div(row["owner"], cls="text-muted small"),
        Button(
            "Open job",
            size="sm",
            hx_get=f"/jobs/{row['id']}",
            hx_target="#job-detail",
        ),
        cls="d-grid gap-2",
    ),
)

The callable owns its internal markup and may return buttons, links, badges, or HTMX actions. It does not change the table's filtering, sorting, or pagination. Actions rendered only in mobile cards are not automatically added to desktop table cells. mobile_card_attrs is copied to every record surface, so id is rejected. If custom markup emits IDs, make them unique per row.

Mobile Parameters

Parameter Type Default Meaning
mobile_mode "scroll" \| "cards" \| "stack" \| None "scroll" Preserve the table, disable alternate presentation, render a card grid, or render stacked rows on small screens.
mobile_breakpoint "sm" \| "md" \| "lg" \| "xl" \| "xxl" "md" Breakpoint at which the semantic table replaces the mobile view.
mobile_sortable bool True In cards/stack mode, show sort links when endpoint or base_url is configured. Links preserve filters/search, reset to page 1, and use the configured HTMX target.
mobile_title str \| None None Title column; defaults to the first normalized data column.
mobile_subtitle str \| None None Optional subtitle column.
mobile_meta list[str] \| None None Ordered metadata columns. Omitted means remaining columns; [] means none.
mobile_hidden list[str] \| None None Exclude columns from generated mobile presentation only.
mobile_card_cls str \| None None Extra class on each mobile record surface.
mobile_card_attrs dict[str, Any] \| None None HTML/ARIA/data_*/hx_* attributes copied to each surface; id is rejected.
mobile_field_renderers dict[str, Callable[[Any, dict], Any]] \| None None Per-column callable receiving (value, row) for generated metadata fields.
mobile_card_renderer Callable[[dict], Any] \| None None Custom per-row mobile content; receives normalized row data and returns FastHTML content.

Field renderers customize selected generated values; the card renderer replaces the generated layout entirely. With a custom card renderer, mobile_title, mobile_subtitle, mobile_meta, and mobile_field_renderers do not affect output. mobile_hidden is validated but cannot filter arbitrary custom markup: exclude sensitive fields before passing records to the component and enforce authorization in the route.

The inactive representation is hidden with responsive CSS display utilities. When card/stack mode is active, mobile_sortable=True, and a server endpoint or base URL is available, a mobile-only sort control is rendered above the records. It provides links for sortable columns, retains the current filters and search, resets pagination to page 1, and follows the same HTMX/URL behavior as desktop sort headers. Set mobile_sortable=False to omit it. Without endpoint or base_url, no mobile sorting control is emitted because the component cannot construct a meaningful server-side sort request. Avoid emitting the same hard-coded DOM IDs from both table cells and custom cards. Built-in search, sorting, and pagination use the DataTable wrapper target; a custom card renderer owns the HTMX behavior of its action controls and should set the intended target explicitly (it may be a detail panel rather than the table wrapper). Use CollectionView when the desktop and mobile surfaces are distinct (such as an Explorer-style browser); use DataTable when table operations and its server-side contract remain central.


Server-Side Contract

When you pass an endpoint, DataTable emits these query params:

  • sort
  • direction
  • page
  • per_page
  • q (or your search_param)
  • any filters you provide
DataTable(
    data,
    endpoint="/users",
    sortable=True,
    searchable=True,
    pagination=True,
    hx_target="#table",
    hx_swap="outerHTML",
    push_url=True,
)

Server-Side Pagination Cookbook

When your dataset exceeds a few hundred rows, you should paginate server-side. This section shows the complete round-trip pattern.

Server Route

Your FastHTML route reads the query params emitted by DataTable, validates them, queries your database, and returns the rendered table:

from fasthtml.common import FastHTML, Titled
from faststrap import DataTable

app = FastHTML()

ALLOWED_SORT = {"name", "email", "created_at", "status"}

@app.get("/users")
def users_page(sort: str = "name", direction: str = "asc",
                page: int = 1, per_page: int = 25, q: str = ""):
    # Validate sort column
    if sort not in ALLOWED_SORT:
        sort = "name"
    if direction not in ("asc", "desc"):
        direction = "asc"
    per_page = min(max(per_page, 1), 100)  # clamp

    # Query your database here (example uses in-memory data)
    data = query_users(sort=sort, direction=direction,
                       search=q, page=page, per_page=per_page)
    total = count_users(search=q)

    return Titled(
        "Users",
        DataTable(
            data,
            sortable=True,
            searchable=True,
            pagination=True,
            page=page,
            per_page=per_page,
            total_rows=total,
            sort=sort,
            direction=direction,
            search=q,
            endpoint="/users",
            hx_target="#users-table",
            hx_swap="outerHTML",
            push_url=True,
            id="users-table",
        ),
    )

Client-Side Rendering

On the initial page load, render the table with endpoint pointing to your server route:

from faststrap import DataTable

DataTable(
    initial_data,
    sortable=True,
    searchable=True,
    pagination=True,
    per_page=25,
    total_rows=total_count,
    endpoint="/users",
    hx_target="#users-table",
    hx_swap="outerHTML",
    push_url=True,
    id="users-table",
)

What Happens

  1. User clicks a column header → DataTable emits HTMX GET to /users?sort=name&direction=desc&page=1
  2. Server validates sort/direction, queries the database, returns the re-rendered table
  3. HTMX swaps the table body via hx_swap="outerHTML"
  4. push_url=True updates the browser URL so the current state is shareable

Helper Functions

Use the helper functions to reuse the current query state for export buttons, links, and related actions:

from faststrap import datatable_query_params, datatable_page_url, datatable_export_params

# Build a link to page 3 with current sort/search preserved
url = datatable_page_url("/users", page=3, sort="email", direction="asc", search="alice")

# Build export params matching the current table state
params = datatable_export_params(sort="name", direction="desc", search="bob", filters={"team": "ops"})

# Build query params for custom links
qp = datatable_query_params(sort="created_at", direction="desc", page=2, per_page=50)

These helpers are available both as top-level imports and as convenience attributes on DataTable:

DataTable.query_params(sort="name", direction="asc")
DataTable.export_params(sort="name", filters={"active": True})
DataTable.page_url("/users", page=5, per_page=25)

Filters and Base URL

Use filters to preserve extra query params in pagination and sort links. Use base_url if you are not using HTMX. When you pass sort or search, DataTable applies that state to the rendered rows so the UI stays consistent with the current request.

DataTable(
    data,
    filters={"team": "ops"},
    base_url="/users",
)

Export Integration

Use the helpers to reuse the table query state for exports, links, and handlers. They are available both as top-level helpers and as convenience attributes on DataTable:

from faststrap import datatable_export_params, ExportButton

params = datatable_export_params(
    sort="name",
    direction="asc",
    search="alice",
    filters={"team": "ops"},
)

ExportButton("Export CSV", endpoint="/export", export_format="csv", extra_params=params)

Build the same query contract for non-export actions:

from faststrap import datatable_query_params

params = datatable_query_params(
    sort="name",
    direction="asc",
    search="alice",
    filters={"team": "ops"},
    page=2,
    per_page=25,
)

Build one page URL while preserving table state:

from faststrap import datatable_page_url

url = datatable_page_url(
    "/users?view=active",
    page=3,
    per_page=25,
    sort="name",
    search="alice",
    filters={"team": "ops"},
)

Theming and Layout

DataTable respects Bootstrap table styles:

  • striped=True
  • hover=True
  • bordered=True
  • responsive=True or responsive="md"

You can also pass table_cls and table_attrs to control the inner table element.


Accessibility

DataTable renders semantic table markup (<table>, <thead>, <tbody>). Use short, descriptive column names for screen readers.


Security Notes

  • Validate sort and direction server-side to avoid unsafe column injection.
  • Enforce per_page limits to prevent excessive responses.
  • Sanitize search strings before using them in SQL or ORM queries.

API Reference

faststrap.components.display.data_table.DataTable(data, *, columns=None, header_map=None, max_rows=None, include_index=False, empty_text='No data available', none_as='', striped=True, hover=True, bordered=False, responsive=True, sortable=False, sort=None, direction='asc', searchable=False, search=None, search_param='q', search_placeholder='Search...', search_debounce=300, pagination=False, page=1, per_page=25, total_rows=None, endpoint=None, base_url=None, filters=None, hx_target=None, hx_swap='outerHTML', poll_interval=None, poll_morph=False, push_url=False, table_id=None, table_cls=None, table_attrs=None, mobile_mode='scroll', mobile_breakpoint='md', mobile_sortable=True, mobile_title=None, mobile_subtitle=None, mobile_meta=None, mobile_hidden=None, mobile_card_cls=None, mobile_card_attrs=None, mobile_card_renderer=None, mobile_field_renderers=None, **kwargs)

DataTable with optional sorting, search, and pagination.

Parameters:

Name Type Description Default
data Any

List of dicts or pandas/polars DataFrame.

required
columns list[str] | None

Optional column order.

None
header_map dict[str, str] | None

Optional display name mapping for headers.

None
max_rows int | None

Optional max rows to render (pre-pagination).

None
include_index bool

Include index column for DataFrame or list data.

False
empty_text str

Text to display when no records exist.

'No data available'
none_as str

Substitute for None values.

''
striped bool

Enable zebra striping.

True
hover bool

Enable row hover styles.

True
bordered bool

Enable borders.

False
responsive bool | ResponsiveType

Wrap table in Bootstrap responsive container.

True
sortable bool | list[str]

True for all columns or a list of sortable columns.

False
sort str | None

Current sort column.

None
direction SortableDirection

Current sort direction.

'asc'
searchable bool

Render a search input.

False
search str | None

Current search value.

None
search_param str

Query param name for search.

'q'
search_placeholder str

Placeholder text for search input.

'Search...'
search_debounce int

Debounce (ms) for HTMX search input.

300
pagination bool

Enable pagination controls.

False
page int

Current page (1-indexed).

1
per_page int

Rows per page.

25
total_rows int | None

Total rows across all pages (server-side).

None
endpoint str | None

HTMX endpoint for server-side updates.

None
base_url str | None

Base URL for standard links (fallback).

None
filters dict[str, Any] | None

Extra query params to preserve in links.

None
hx_target str | None

HTMX target selector.

None
hx_swap str | None

HTMX swap strategy for links/search.

'outerHTML'
push_url bool

If True, enable hx-push-url for links.

False
table_id str | None

Explicit wrapper id (auto-generated if omitted).

None
table_cls str | None

Extra CSS classes for the table element.

None
mobile_mode MobileMode

"scroll" retains the responsive table. "cards" renders a responsive card grid below mobile_breakpoint; "stack" renders flatter stacked record rows there.

'scroll'
mobile_breakpoint ResponsiveType

Bootstrap breakpoint where cards change back to the semantic table.

'md'
mobile_sortable bool

Show a compact sort control in cards/stack mode when a server endpoint or base URL is configured.

True
mobile_title str | None

Column used as each card title. Defaults to the first data column.

None
mobile_subtitle str | None

Optional column rendered beneath the title.

None
mobile_meta list[str] | None

Columns rendered as labeled metadata in each card.

None
mobile_hidden list[str] | None

Columns excluded from generated mobile cards.

None
mobile_card_cls str | None

Extra classes applied to every generated mobile card.

None
mobile_card_attrs dict[str, Any] | None

Attributes applied to every generated mobile card. Do not include id because one attribute set is reused for multiple records.

None
mobile_card_renderer Callable[[dict[str, Any]], Any] | None

Optional callable that receives a row dictionary and returns custom FastHTML content for its mobile presentation.

None
mobile_field_renderers dict[str, Callable[[Any, dict[str, Any]], Any]] | None

Mapping of column names to callables receiving (value, row) and returning content for that mobile field.

None
table_attrs dict[str, Any] | None

Extra attributes applied to the table element.

None
**kwargs Any

Additional HTML attributes for the wrapper.

{}
Source code in src/faststrap/components/display/data_table.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
@register(category="display")
@beta
def DataTable(
    data: Any,
    *,
    columns: list[str] | None = None,
    header_map: dict[str, str] | None = None,
    max_rows: int | None = None,
    include_index: bool = False,
    empty_text: str = "No data available",
    none_as: str = "",
    striped: bool = True,
    hover: bool = True,
    bordered: bool = False,
    responsive: bool | ResponsiveType = True,
    sortable: bool | list[str] = False,
    sort: str | None = None,
    direction: SortableDirection = "asc",
    searchable: bool = False,
    search: str | None = None,
    search_param: str = "q",
    search_placeholder: str = "Search...",
    search_debounce: int = 300,
    pagination: bool = False,
    page: int = 1,
    per_page: int = 25,
    total_rows: int | None = None,
    endpoint: str | None = None,
    base_url: str | None = None,
    filters: dict[str, Any] | None = None,
    hx_target: str | None = None,
    hx_swap: str | None = "outerHTML",
    poll_interval: int | None = None,
    poll_morph: bool = False,
    push_url: bool = False,
    table_id: str | None = None,
    table_cls: str | None = None,
    table_attrs: dict[str, Any] | None = None,
    mobile_mode: MobileMode = "scroll",
    mobile_breakpoint: ResponsiveType = "md",
    mobile_sortable: bool = True,
    mobile_title: str | None = None,
    mobile_subtitle: str | None = None,
    mobile_meta: list[str] | None = None,
    mobile_hidden: list[str] | None = None,
    mobile_card_cls: str | None = None,
    mobile_card_attrs: dict[str, Any] | None = None,
    mobile_card_renderer: Callable[[dict[str, Any]], Any] | None = None,
    mobile_field_renderers: dict[str, Callable[[Any, dict[str, Any]], Any]] | None = None,
    **kwargs: Any,
) -> Div:
    """DataTable with optional sorting, search, and pagination.

    Args:
        data: List of dicts or pandas/polars DataFrame.
        columns: Optional column order.
        header_map: Optional display name mapping for headers.
        max_rows: Optional max rows to render (pre-pagination).
        include_index: Include index column for DataFrame or list data.
        empty_text: Text to display when no records exist.
        none_as: Substitute for None values.
        striped: Enable zebra striping.
        hover: Enable row hover styles.
        bordered: Enable borders.
        responsive: Wrap table in Bootstrap responsive container.
        sortable: True for all columns or a list of sortable columns.
        sort: Current sort column.
        direction: Current sort direction.
        searchable: Render a search input.
        search: Current search value.
        search_param: Query param name for search.
        search_placeholder: Placeholder text for search input.
        search_debounce: Debounce (ms) for HTMX search input.
        pagination: Enable pagination controls.
        page: Current page (1-indexed).
        per_page: Rows per page.
        total_rows: Total rows across all pages (server-side).
        endpoint: HTMX endpoint for server-side updates.
        base_url: Base URL for standard links (fallback).
        filters: Extra query params to preserve in links.
        hx_target: HTMX target selector.
        hx_swap: HTMX swap strategy for links/search.
        push_url: If True, enable hx-push-url for links.
        table_id: Explicit wrapper id (auto-generated if omitted).
        table_cls: Extra CSS classes for the table element.
        mobile_mode: ``"scroll"`` retains the responsive table. ``"cards"``
            renders a responsive card grid below ``mobile_breakpoint``;
            ``"stack"`` renders flatter stacked record rows there.
        mobile_breakpoint: Bootstrap breakpoint where cards change back to the
            semantic table.
        mobile_sortable: Show a compact sort control in cards/stack mode when
            a server endpoint or base URL is configured.
        mobile_title: Column used as each card title. Defaults to the first
            data column.
        mobile_subtitle: Optional column rendered beneath the title.
        mobile_meta: Columns rendered as labeled metadata in each card.
        mobile_hidden: Columns excluded from generated mobile cards.
        mobile_card_cls: Extra classes applied to every generated mobile card.
        mobile_card_attrs: Attributes applied to every generated mobile card.
            Do not include ``id`` because one attribute set is reused for
            multiple records.
        mobile_card_renderer: Optional callable that receives a row dictionary
            and returns custom FastHTML content for its mobile presentation.
        mobile_field_renderers: Mapping of column names to callables receiving
            ``(value, row)`` and returning content for that mobile field.
        table_attrs: Extra attributes applied to the table element.
        **kwargs: Additional HTML attributes for the wrapper.
    """
    cfg = resolve_defaults(
        "DataTable",
        striped=striped,
        hover=hover,
        bordered=bordered,
        responsive=responsive,
        sortable=sortable,
        searchable=searchable,
        pagination=pagination,
        per_page=per_page,
        direction=direction,
        empty_text=empty_text,
        none_as=none_as,
    )

    c_striped = cfg.get("striped", striped)
    c_hover = cfg.get("hover", hover)
    c_bordered = cfg.get("bordered", bordered)
    c_responsive = cfg.get("responsive", responsive)
    c_sortable = cfg.get("sortable", sortable)
    c_searchable = cfg.get("searchable", searchable)
    c_pagination = cfg.get("pagination", pagination)

    if mobile_mode not in {None, "scroll", "cards", "stack"}:
        raise ValueError("mobile_mode must be None, 'scroll', 'cards', or 'stack'")
    if mobile_breakpoint not in {"sm", "md", "lg", "xl", "xxl"}:
        raise ValueError("mobile_breakpoint must be a Bootstrap breakpoint")
    c_per_page = cfg.get("per_page", per_page)
    c_direction = cfg.get("direction", direction)
    c_empty_text = cfg.get("empty_text", empty_text)
    c_none_as = cfg.get("none_as", none_as)

    if c_pagination and page < 1:
        msg = f"page must be >= 1, got {page}"
        raise ValueError(msg)
    if c_pagination and c_per_page < 1:
        msg = f"per_page must be >= 1, got {c_per_page}"
        raise ValueError(msg)

    resolved_columns, records, index_values = _normalize_table_data(
        data,
        columns=columns,
        max_rows=max_rows,
        include_index=include_index,
    )
    mobile_columns = set(resolved_columns)
    requested_mobile_columns = set(mobile_meta or []) | set(mobile_hidden or [])
    requested_mobile_columns.update(mobile_field_renderers or {})
    if mobile_title is not None:
        requested_mobile_columns.add(mobile_title)
    if mobile_subtitle is not None:
        requested_mobile_columns.add(mobile_subtitle)
    unknown_mobile_columns = requested_mobile_columns - mobile_columns
    if unknown_mobile_columns:
        names = ", ".join(sorted(unknown_mobile_columns))
        raise ValueError(f"Unknown mobile column(s): {names}")

    if isinstance(c_sortable, list):
        sortable_columns = [col for col in c_sortable if col in resolved_columns]
    elif c_sortable:
        sortable_columns = list(resolved_columns)
    else:
        sortable_columns = []

    if search:
        filtered_records: list[dict[str, Any]] = []
        filtered_index_values: list[str] | None = [] if index_values is not None else None
        for idx, row in enumerate(records):
            current_index = index_values[idx] if index_values is not None else None
            if _matches_search(
                row,
                columns=resolved_columns,
                query=search,
                index_value=current_index if include_index else None,
            ):
                filtered_records.append(row)
                if filtered_index_values is not None and current_index is not None:
                    filtered_index_values.append(current_index)
        records = filtered_records
        if filtered_index_values is not None:
            index_values = filtered_index_values

    if sort not in sortable_columns:
        sort = None
    elif endpoint is None:
        active_sort = cast(str, sort)
        indexed_records = list(enumerate(records))
        indexed_records.sort(
            key=lambda item: _sort_key(item[1].get(active_sort)),
            reverse=c_direction == "desc",
        )
        records = [record for _, record in indexed_records]
        if index_values is not None:
            index_values = [index_values[idx] for idx, _ in indexed_records]

    full_count = len(records)
    total_count = total_rows if total_rows is not None else full_count

    if c_pagination and endpoint is None and base_url is None:
        total_pages = math.ceil(total_count / c_per_page) if total_count else 1
        start = (page - 1) * c_per_page
        records = records[start : start + c_per_page]
        if index_values is not None:
            index_values = index_values[start : start + c_per_page]
    elif c_pagination:
        total_pages = math.ceil(total_count / c_per_page) if total_count else 1
    else:
        total_pages = 1

    visible_columns = list(resolved_columns)
    if include_index:
        visible_columns = ["index", *visible_columns]

    wrapper_id = kwargs.pop("id", None) or table_id
    if wrapper_id is None:
        wrapper_id = uniquify_id(
            _stable_table_id(
                columns=visible_columns,
                row_count=full_count,
                include_index=include_index,
                sortable=bool(sortable_columns),
                searchable=c_searchable,
                pagination=c_pagination,
            )
        )

    if hx_target is None:
        hx_target = f"#{wrapper_id}"

    link_base = endpoint or base_url

    base_params: dict[str, Any] = {}
    if filters:
        base_params.update(filters)
    if c_pagination:
        base_params["per_page"] = c_per_page
    if search:
        base_params[search_param] = search
    if sort:
        base_params["sort"] = sort
        base_params["direction"] = c_direction

    effective_hx_swap = "morph" if (poll_morph and hx_swap == "outerHTML") else hx_swap

    head_cells: list[Any] = []
    for col in visible_columns:
        header_label = (header_map or {}).get(col, col)
        if col in sortable_columns and link_base:
            current = sort == col
            next_dir: SortableDirection = "desc" if current and c_direction == "asc" else "asc"
            params = {**base_params, "sort": col, "direction": next_dir, "page": page}
            url = _build_url(link_base, params)
            link = A(
                header_label,
                (
                    Span(
                        "asc" if current and c_direction == "asc" else "desc",
                        cls="ms-1 text-muted small",
                    )
                    if current
                    else None
                ),
                cls="text-decoration-none",
                **_link_attrs(
                    url,
                    endpoint=endpoint,
                    hx_target=hx_target,
                    hx_swap=effective_hx_swap,
                    push_url=push_url,
                ),
            )
            aria_sort = (
                "ascending"
                if current and c_direction == "asc"
                else "descending" if current else None
            )
            head_cells.append(TCell(link, header=True, scope="col", aria_sort=aria_sort))
        else:
            head_cells.append(TCell(header_label, header=True, scope="col"))

    thead = THead(TRow(*head_cells))

    if not records:
        tbody = TBody(
            TRow(
                TCell(
                    c_empty_text,
                    colspan=max(1, len(visible_columns)),
                    cls="text-center text-muted",
                )
            )
        )
    else:
        body_rows: list[Any] = []
        for idx, row in enumerate(records):
            row_cells: list[Any] = []
            if include_index and index_values is not None:
                row_cells.append(TCell(index_values[idx], header=True, scope="row"))

            for col in resolved_columns:
                value = row.get(col)
                rendered = c_none_as if value is None else str(value)
                row_cells.append(TCell(rendered))

            body_rows.append(TRow(*row_cells))

        tbody = TBody(*body_rows)

    table_kwargs = table_attrs.copy() if table_attrs else {}
    table_kwargs["cls"] = merge_classes(table_kwargs.get("cls"), table_cls)

    table = Table(
        thead,
        tbody,
        striped=c_striped,
        hover=c_hover,
        bordered=c_bordered,
        responsive=c_responsive,
        **table_kwargs,
    )

    parts: list[Any] = []

    if c_searchable:
        input_attrs: dict[str, Any] = {
            "type": "search",
            "name": search_param,
            "value": search or "",
            "placeholder": search_placeholder,
            "cls": "form-control",
            "autocomplete": "off",
        }
        if endpoint:
            input_attrs.update(
                {
                    "hx_get": link_base,
                    "hx_target": hx_target,
                    "hx_trigger": f"keyup changed delay:{search_debounce}ms",
                    "hx_swap": effective_hx_swap,
                }
            )
            if push_url:
                input_attrs["hx_push_url"] = "true"
        hidden_inputs: list[Any] = []
        preserved_params = filters.copy() if filters else {}
        if sort:
            preserved_params["sort"] = sort
            preserved_params["direction"] = c_direction
        if c_pagination:
            preserved_params["per_page"] = c_per_page
            preserved_params["page"] = 1

        for key, value in preserved_params.items():
            normalized = _normalize_query_value(value)
            if normalized is None or str(key) == search_param:
                continue
            if isinstance(normalized, list):
                hidden_inputs.extend(
                    Input(type="hidden", name=str(key), value=item) for item in normalized
                )
            else:
                hidden_inputs.append(Input(type="hidden", name=str(key), value=normalized))

        search_form_attrs: dict[str, Any] = {"cls": "mb-3"}
        if link_base and not endpoint:
            search_form_attrs["method"] = "get"
            search_form_attrs["action"] = link_base

        search_form = Form(
            *hidden_inputs,
            Input(**input_attrs),
            **search_form_attrs,
        )
        parts.append(search_form)

    if mobile_mode in {"cards", "stack"}:
        parts.append(Div(table, cls=f"d-none d-{mobile_breakpoint}-block"))
        if mobile_sortable and sortable_columns and link_base:
            sort_links: list[Any] = []
            for col in sortable_columns:
                current = sort == col
                mobile_next_dir: SortableDirection = (
                    "desc" if current and c_direction == "asc" else "asc"
                )
                params = {**base_params, "sort": col, "direction": mobile_next_dir}
                if c_pagination:
                    params["page"] = 1
                url = _build_url(link_base, params)
                label = (header_map or {}).get(col, col)
                sort_links.append(
                    A(
                        label,
                        Span(" (sorted)" if current else "", cls="visually-hidden"),
                        cls=merge_classes(
                            "btn btn-sm",
                            "btn-primary" if current else "btn-outline-secondary",
                        ),
                        aria_label=f"Sort by {label}"
                        + (f", currently {c_direction}" if current else ""),
                        **_link_attrs(
                            url,
                            endpoint=endpoint,
                            hx_target=hx_target,
                            hx_swap=effective_hx_swap,
                            push_url=push_url,
                        ),
                    )
                )
            parts.append(
                Div(
                    Span("Sort:", cls="small fw-semibold me-1"),
                    *sort_links,
                    cls=f"d-{mobile_breakpoint}-none d-flex flex-wrap align-items-center gap-2 mb-3",
                    role="group",
                    aria_label="Sort records",
                )
            )
        parts.append(
            _mobile_presentation(
                records,
                columns=resolved_columns,
                header_map=header_map,
                none_as=c_none_as,
                title_column=mobile_title,
                subtitle_column=mobile_subtitle,
                meta_columns=mobile_meta,
                hidden_columns=mobile_hidden,
                card_cls=mobile_card_cls,
                card_attrs=mobile_card_attrs,
                card_renderer=mobile_card_renderer,
                field_renderers=mobile_field_renderers,
                mode=cast(Literal["cards", "stack"], mobile_mode),
                breakpoint=mobile_breakpoint,
                empty_text=c_empty_text,
                reserved_id=wrapper_id,
            )
        )
    else:
        parts.append(table)

    if c_pagination and total_pages > 1:
        pager_links: list[Any] = []
        for page_num in _pagination_window(page, total_pages):
            if page_num is None:
                pager_links.append(
                    Li(
                        Span("...", cls="page-link"),
                        cls="page-item disabled",
                        aria_hidden="true",
                    )
                )
                continue
            active = page_num == page
            if link_base:
                params = {**base_params, "page": page_num}
                url = _build_url(link_base, params)
                link = A(
                    str(page_num),
                    cls="page-link",
                    **_link_attrs(
                        url,
                        endpoint=endpoint,
                        hx_target=hx_target,
                        hx_swap=effective_hx_swap,
                        push_url=push_url,
                    ),
                )
            else:
                link = Span(str(page_num), cls="page-link")

            pager_links.append(
                Li(
                    link,
                    cls="page-item" + (" active" if active else ""),
                    aria_current="page" if active else None,
                )
            )

        pager = Nav(
            Ul(*pager_links, cls="pagination"),
            cls="mt-3",
            aria_label="Data table pagination",
        )
        parts.append(pager)

    wrapper_attrs: dict[str, Any] = {
        "id": wrapper_id,
        "cls": merge_classes("faststrap-data-table", kwargs.pop("cls", "")),
    }
    if poll_interval and (endpoint or base_url):
        wrapper_attrs["hx_get"] = endpoint or base_url
        wrapper_attrs["hx_trigger"] = f"every {poll_interval}s"
        wrapper_attrs["hx_target"] = f"#{wrapper_id}"
        wrapper_attrs["hx_swap"] = effective_hx_swap
    wrapper_attrs.update(convert_attrs(kwargs))

    return Div(*parts, **wrapper_attrs)

faststrap.components.display.data_table.datatable_export_params(*, sort=None, direction='asc', search=None, search_param='q', filters=None, include_pagination=False, page=None, per_page=None)

Build query params for exporting DataTable state.

This helper mirrors the DataTable query contract and is intended to be passed into ExportButton(extra_params=...).

Source code in src/faststrap/components/display/data_table.py
def datatable_export_params(
    *,
    sort: str | None = None,
    direction: SortableDirection = "asc",
    search: str | None = None,
    search_param: str = "q",
    filters: dict[str, Any] | None = None,
    include_pagination: bool = False,
    page: int | None = None,
    per_page: int | None = None,
) -> dict[str, Any]:
    """Build query params for exporting DataTable state.

    This helper mirrors the DataTable query contract and is intended to be passed
    into ExportButton(extra_params=...).
    """
    params: dict[str, Any] = {}

    if filters:
        for key, value in filters.items():
            normalized = _normalize_query_value(value)
            if normalized is None:
                continue
            params[str(key)] = normalized

    if sort:
        params["sort"] = sort
        params["direction"] = direction

    if search is not None:
        params[search_param] = search

    if include_pagination:
        if page is not None:
            params["page"] = page
        if per_page is not None:
            params["per_page"] = per_page

    return params

faststrap.components.display.data_table.datatable_query_params(*, sort=None, direction='asc', search=None, search_param='q', filters=None, page=None, per_page=None)

Build the common DataTable query contract for links and handlers.

Source code in src/faststrap/components/display/data_table.py
def datatable_query_params(
    *,
    sort: str | None = None,
    direction: SortableDirection = "asc",
    search: str | None = None,
    search_param: str = "q",
    filters: dict[str, Any] | None = None,
    page: int | None = None,
    per_page: int | None = None,
) -> dict[str, Any]:
    """Build the common DataTable query contract for links and handlers."""
    return datatable_export_params(
        sort=sort,
        direction=direction,
        search=search,
        search_param=search_param,
        filters=filters,
        include_pagination=page is not None or per_page is not None,
        page=page,
        per_page=per_page,
    )

faststrap.components.display.data_table.datatable_page_url(base_url, *, page, per_page=None, sort=None, direction='asc', search=None, search_param='q', filters=None)

Build a URL for one DataTable page while preserving current state.

Source code in src/faststrap/components/display/data_table.py
def datatable_page_url(
    base_url: str,
    *,
    page: int,
    per_page: int | None = None,
    sort: str | None = None,
    direction: SortableDirection = "asc",
    search: str | None = None,
    search_param: str = "q",
    filters: dict[str, Any] | None = None,
) -> str:
    """Build a URL for one DataTable page while preserving current state."""
    params = datatable_query_params(
        sort=sort,
        direction=direction,
        search=search,
        search_param=search_param,
        filters=filters,
        page=max(1, page),
        per_page=per_page,
    )
    return _build_url(base_url, params)

When using mobile_card_renderer or mobile_field_renderers, ensure generated element IDs are unique across all cards and do not collide with the DataTable wrapper ID. Duplicate/reserved IDs raise ValueError to prevent invalid duplicate DOM IDs in the dual desktop/mobile markup.