~benaiah/fennel-openresty

ref: 269cbdcd3a8e7bcb045c7731f51c80f524a9c6b0 fennel-openresty/server/html.fnl -rw-r--r-- 1.0 KiB
269cbdcdBenaiah Mischenko Initial OpenResty+Fennel setup 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
;; borrowed from https://github.com/technomancy/fennel-lang.org/blob/3c5d70e2edf9434dc7b7582015b0457da448c87b/html.fnl

;; A *very* basic HTML generation library.
;; No escaping features; never use this on user input!

(local map (fn [f tbl]
             (let [out {}]
               (each [i v (ipairs tbl)]
                 (tset out i (f v)))
               out)))

(local map-kv (fn [f tbl]
                (let [out {}]
                  (each [k v (pairs tbl)]
                    (table.insert out (f k v)))
                  out)))

(local to-attr (fn [k v]
                 (if (= v true) k
                     (.. k "=\"" v"\""))))

(local tag (fn [tag-name attrs]
             (assert (= (type attrs) "table") "Missing attrs table")
             (let [attr-str (table.concat (map-kv to-attr attrs) " ")]
               (.. "<" tag-name " " attr-str">"))))

(fn html [doc]
  (if (= (type doc) "string")
      doc
      (let [[tag-name attrs & body] doc]
        (.. (tag tag-name attrs)
            (table.concat (map html body) " ")
"</" tag-name ">"))))