Using HTMX

HTMX is an incredibly simple, HTML-first library.
Instead of going through HTML->JS->JSON-API loop/mess, you can go directly HTML->HTML-API.
Basically you just return HTML snippets that get included where you want in your page.

Sharaf is using the hepek-components as its template engine, which has support for HTMX attributes.

You can lots of examples in examples/scala-cli/htmx folder.


Let's make a simple page that triggers a POST request to fetch a HTML snippet.
Create a file htmx_load_snippet.sc and paste this code into it:

    //> using scala "3.4.0"
//> using dep ba.sake::sharaf:0.4.0

import io.undertow.Undertow
import scalatags.Text.all.*
import ba.sake.hepek.html.HtmlPage
import ba.sake.hepek.htmx.*
import ba.sake.sharaf.*, routing.*

object IndexView extends HtmlPage with HtmxDependencies:
  override def bodyContent =
    button(hx.post := "/html-snippet", hx.swap := "outerHTML")("Click here!")

val routes = Routes:
  case GET() -> Path() =>
    Response.withBody(IndexView)
  case POST() -> Path("html-snippet") =>
    Response.withBody(
      div(
        b("WOW, it works! 😲"),
        div("Look ma, no JS! 😎")
      )
    )

Undertow.builder
  .addHttpListener(8181, "localhost")
  .setHandler(SharafHandler(routes))
  .build
  .start()

println(s"Server started at http://localhost:8181")

and run it like this:

scala-cli html.sc 

Go to http://localhost:8181
to see how it works.