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
| Name | Status | |
|---|---|---|
| Ada Lovelace | ada@example.com | Active |
| Alan Turing | alan@example.com | Invited |
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,
)
Sorting and Search
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:
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.
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:
sortdirectionpageper_pageq(or yoursearch_param)- any
filtersyou 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
- User clicks a column header →
DataTableemits HTMX GET to/users?sort=name&direction=desc&page=1 - Server validates
sort/direction, queries the database, returns the re-rendered table - HTMX swaps the table body via
hx_swap="outerHTML" push_url=Trueupdates 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:
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.
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=Truehover=Truebordered=Trueresponsive=Trueorresponsive="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
sortanddirectionserver-side to avoid unsafe column injection. - Enforce
per_pagelimits 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'
|
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 |
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
|
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 | |
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
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
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
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.