Hello htmx
htmx gives you access to AJAX , CSS Transitions , WebSockets , and Server Sent Events directly in HTML, using attributes , so you can build modern user interfaces with the simplicity power of hypertext1
I know almost nothing about it, but I like their Twitter feed.
A real world example
I know enough to install htmx and trigger a GET request when a button is clicked. Let’s jump right in with a real world example.
The following code, added (currently only to the development version) of this site’s
render-link.html template
, renders a button element after any internal link elements. Since this is just an experiment
(related to
notes / Literary Machines
), the buttons are only added
to pages that have infolinks = true in their metadata:
{{- if .Page.Params.infolinks }}
{{ $rel := $attrs.rel }}
{{- if not $rel }}
{{ $fragmentsMap := site.Data.fragments.sections }}
{{ $url := $attrs.href }}
{{ $fragmentData := index $fragmentsMap $url }}
{{- if $fragmentData }}
{{ $dbId := $fragmentData.db_id }}
{{ $apiUrl := site.Params.apiUrl }}
<button class="infolink"
hx-get="{{ $apiUrl }}/fragment/{{ $dbId }}"
hx-target="#fragment-display-{{ $dbId }}">?</button>
<div id="fragment-display-{{ $fragmentData.db_id}}" class="infolink-display"></div>
{{- end }}
{{- end }}
{{- end }}
Clicking the button triggers a GET request to $site.Params.apiUrl. The request is handled by a
FastAPI
application.
With no validation or error handling (I just want see it working):
@app.get("/fragment/{row_id}", response_class=HTMLResponse)
async def get_fragment(
row_id, db: aiosqlite.Connection = Depends(get_db_connection, scope="function")
):
cursor = await db.execute(
f"SELECT html_heading, html_fragment FROM sections WHERE id = {row_id}"
)
row = await cursor.fetchone()
if row:
return row[1]
else:
return "<p>Something went wrong</p>"
Initial results
There are some obvious issues with the UI, but it works.
Related
References
htmx.org. “htmx.” htmx.org
htmx.org. “htmx Documentation.” htmx.org/docs/
Fielding, Roy Thomas. “Architectural Styles and the Design of Network-based Software Architecture.” University of California, Irvine, 2000. https://roy.gbiv.com/pubs/dissertation/fielding_dissertation.pdf .