liveBook · Manning

Hx-swap

As explained in Django in Action

hx-swap is an HTMX attribute that specifies how returned HTML is inserted into or used to replace a target element.

hx-swap tells HTMX how returned HTML changes a target element. Used with hx-target, it turns a server response into a focused page update instead of reloading the whole page. section 12.2 section 12.7

Replacing a random song

A link can request another song and replace the contents of the element selected by hx-target: <a hx-get="/random-song" hx-target="#song" hx-swap="innerHTML">Another song</a>. The view returns an HTML partial, and HTMX inserts it inside #song. section 12.2

Read the two attributes as a small division of labor:

  • hx-target identifies which tag receives the update, using a CSS selector. section 12.7
  • hx-swap identifies which part of that tag changes; innerHTML replaces the contents inside it. section 12.2
  • The server response is typically a partial rather than a complete page, while Django continues using ordinary view mechanisms. section 12.2 section 12.7
Figure 12.1 Using HTMX attributes to change a link into an action that replaces a portion of the page
figure

Trace the request, partial response, target selection, and replacement flow in the interaction diagram. section 12.2

How Django in Action covers it

How deep it goes
Defines innerHTML replacement and separates target selection from swap behavior, without enumerating other swap values.
Examples
Uses a random-song link that fetches an HTML partial and replaces a page region.
What it assumes
Assumes HTTP methods and Django views while explaining returned fragments as partials.
What you can do after
Apply it via HTMX to replace the contents of a selected element with returned HTML.
How it connects
Connects HTMX partials, hx-target, hx-get, HTTP requests, and Django views.

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.