Active Search

Demonstrates the active search box pattern

HOME | Explain | Code | Htmx Docs | Full screen
import time
from pathlib import Path

from fasthtml.common import H3, Div, Img, Input, Span, Table, Tbody, Td, Th, Thead, Tr, fast_app

app, rt = fast_app()


@app.get
def page():
    return Div(
        H3("Search Contacts"),
        Input(
            hx_post=search, hx_target="#results",
            hx_trigger="input changed delay:500ms, search", hx_indicator=".htmx-indicator",
            type="search", name="query", placeholder="Begin Typing To Search Users...",
        ),
        Span(Img(src="/img/bars.svg"), "Searching...", cls="htmx-indicator"),
        Table(
            Thead(Tr(Th("First Name"), Th("Last Name"), Th("Email"))),
            Tbody(id="results"),
        ),
    )


@app.post
def search(query: str, limit: int = 10):
    time.sleep(0.5)
    data = [x.split(",") for x in LINES if query.lower() in x.lower()]
    return [Tr(Td(x[0]), Td(x[1]), Td(x[2])) for x in data[:limit]]


LINES = Path("public/data/contacts.csv").read_text().splitlines()

Server Calls