clojure-demos/reagent-reitit-demo/resources/public/documents/dsl-demo.org

2.3 KiB

Intro to HoneySQL & Hiccup

Hiccup

https://github.com/weavejester/hiccup hiccup is a html DSL, used extensively in the clojure's eco-system, there are others as well but hiccup is the most widely used.

In hiccup everything is a list, this means you can easily compose html using standard language constructs. To render the hiccup to html elements we call the (html) function from the hiccup library for server side with reagent or client side code this will likely be a different function like (render).

Simple examples

If using reagent you don't need to pass into h/html but this is server side reagent also has some helpers to work with react nicer.

[:span "bar"]

Attributes are added as a map of values styles are also a map

[:span {:class "class1 class2" :title "my title" :style {:color "red"}} "bar"]

You can use shorthand to add id's and classes

[:span#id.class1.class2 "bar"]

Compossible components

The main advantage comes from the ability to compose the parts together, so we can break this into function's

In this example its only a hash map, the data is separated out from the html, in reagent you can use atom for live updating.

(defn navbar-link [{:keys [href title text] :or {text nil title nil}}]
  [:a.link.dim.white.dib.mr3 {:href href :title title} text])

(defn navbar [links]
  [:header.bg-black-90.fixed.w-100.ph3.pv3.pv4-ns.ph4-m.ph5-l
   (into [:nav.f6.fw6.ttu.tracked]
    (map navbar-link links))])

(navbar [{:href "link1" :title "title here"}
         {:href "link2" :title nil}
         {:href "link3" :text "link text"}
         {:href "link4"}])

You can use clojure core language to manipulate these lists.

place parts inside another containing element

(into [:div.container]
      [[:span "span 1"]
       [:span "span 2"]])

You could also use merge

(merge [:span "span 1"] [:span "span 2"] [:span "span 3"])

We can take advantage of lazyness if we like

(take 2 (map navbar-link
             [{:key "link1" :href "link1" :title "title here"}
              {:key "link2" :href "link2" :title nil}
              {:key "link3" :href "link3" :text "link text"}
              {:key "link4" :href "link4"}]))