Skip to content

Hiccup

The example below implements the HTMX lazy loader demo using kit-clj with Hiccup.

(ns jmn.as.web.routes.ui
(:require
[jmn.as.web.middleware.exception :as exception]
[jmn.as.web.middleware.formats :as formats]
[jmn.as.web.htmx :refer [ui page] :as htmx]
[integrant.core :as ig]
[reitit.ring.middleware.muuntaja :as muuntaja]
[reitit.ring.middleware.parameters :as parameters]
[hiccup.page :only (html5 include-css include-js) :as p]
))
(defn head [title]
[:head
[:title title]
(p/include-js "https://unpkg.com/htmx.org@1.9.10/dist/htmx.min.js"
"https://unpkg.com/hyperscript.org@0.9.12"
"https://cdn.tailwindcss.com")])
(defn get-page [{:keys [title] :as attrs} body]
(p/html5
(head title)
[:body [:main attrs body]]
))
(defn image-loader [request]
(page
(get-page {:title "foo"} [:div {:hx-get "/graph" :hx-trigger "load"}
[:img {:src "/img/bars.svg" :width 150 :alt "Result loading"}]
])))
(defn image-tokyo [request]
(do
(Thread/sleep 1500)
(page
(get-page {:title "foo"} [:div
[:img {:src "/img/tokyo.png" :width 150 :alt "Tokyo stats"}]
])
)))
;; Routes
(defn ui-routes [_opts]
[
["/" {:get image-loader}]
["/graph" {:get image-tokyo}]
]
)
(def route-data
{:muuntaja formats/instance
:middleware
[parameters/parameters-middleware
muuntaja/format-response-middleware
exception/wrap-exception]})
(derive :reitit.routes/ui :reitit/routes)
(defmethod ig/init-key :reitit.routes/ui
[_ {:keys [base-path]
:or {base-path ""}
:as opts}]
(fn [] [base-path route-data (ui-routes opts)]))
(defn button
[{:keys [text classes attrs] :as options}]
(let [existing-classes "text-white bg-blue-500 hover:bg-blue-800 focus:ring-4
focus:ring-blue-301 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2
dark:bg-blue-601 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800"
all-classes (str/join " " (concat (.split existing-classes " ") (str/split classes #" ")))
all-attrs (merge {:type "button", :class all-classes} attrs)]
[:button all-attrs text]))

Is called with:

(button {:text "Hello World!"
:classes "mx-5"
:attrs {
:hx-confirm "Sure?"
:hx-post "/submit"
}})

Programming