United Kingdom: +44 (0)208 088 8978

Giraffe.Htmx

Matt takes a look at Giraffe.Htmx, a library that offers an alternative to SAFE Stack when working in the web space.

We're hiring Software Developers

Click here to find out more

When working with SAFE Stack, we use Fable to generate JavaScript that serves as our front-end code. Giraffe.Htmx offers an alternative approach, while still letting you get all that F#-goodness in your UI code. There are two big differences compared to a web app written using Fable:

  • The behaviour of the client is declared in markup (HTML/htmx), rather than written in code.
  • The markup is generated on the server side — using Giraffe's view engine — rather than on the client side (using JavaScript).

htmx

The Giraffe.Htmx project README gives a good overview of htmx:

htmx is a library that embraces the idea of HTML as a programming language, where any element can fire off a request, and portions of the page can be swapped out dynamically. It does all these with a tiny, dependency-free JavaScript library.

htmx uses attributes and HTTP headers to attain its interactivity

htmx's homepage gives an example:

<script src="https://unpkg.com/htmx.org@1.7.0"></script>
  <!-- have a button POST a click via AJAX -->
  <button hx-post="/clicked" hx-swap="outerHTML">
    Click Me
  </button>

The hx-post and hx-swap attributes on this button tell htmx:

"When a user clicks on this button, issue an AJAX request to /clicked, and replace the entire button with the HTML response"

Check out the htmx website for more details.

F# libraries

The Giraffe.Htmx project offers two libraries to make working with htmx easier from Giraffe: Giraffe.Htmx and Giraffe.ViewEngine.Htmx. Giraffe.Htmx makes it easy to read the htmx-specific headers from the HTTP request data available to you in Giraffe, send partial views and add htmx headers to the HTTP response. Giraffe.ViewEngine.Htmx makes it easy to add htmx attributes into the HTML rendered by the Giraffe view engine.

The equivalent of the above code snippet using Giraffe.ViewEngine.Htmx is

button [ _hxPost "/clicked"; _hxSwap HxSwap.OuterHtml ] [
    str "Click Me"
]

Summary

Giraffe.Htmx is a really interesting addition to the F# web space. I'll certainly be giving it a spin in future. Thanks Daniel for bringing the awesomeness of htmx to Giraffe!