~technomancy/fennel-lang.org

ref: 720592c61574fec92d38bf2f884b92d0368c4acc fennel-lang.org/html.fnl -rw-r--r-- 1.8 KiB
720592c6Phil Hagelberg august user group 4 months 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
;; A *very* basic HTML generation library.
;; Basic escaping features only; never use this on user input!

(local entity-replacements {"&" "&" ; must be first!
                            "<" "&lt;"
                            ">" "&gt;"
                            "\"" "&quot;"})

(local void-tags {:area    true
                  :base    true
                  :br      true
                  :col     true
                  :command true
                  :embed   true
                  :hr      true
                  :img     true
                  :input   true
                  :keygen  true
                  :link    true
                  :meta    true
                  :param   true
                  :source  true
                  :track   true
                  :wbr     true})

(fn void-tag? [tag-name]
  (. void-tags tag-name))

(local entity-search
       (.. "[" (table.concat (icollect [k (pairs entity-replacements)] k)) "]"))

(fn escape [s]
  (assert (= (type s) :string))
  (s:gsub entity-search entity-replacements))

(fn tag [tag-name attrs]
  (assert (= (type attrs) "table") (.. "Missing attrs table: " tag-name))
  (let [attr-str (table.concat (icollect [k v (pairs attrs)]
                                 (if (= v true) k
                                     (.. k "=\"" v"\""))) " ")]
    (.. "<" tag-name " " attr-str">")))

(fn html [document allow-no-escape?]
  (if (= (type document) :string)
      (escape document)
      (and allow-no-escape? (= (. document 1) :NO-ESCAPE))
      (. document 2)
      (let [[tag-name attrs & body] document]
        (if (void-tag? tag-name)
            (tag tag-name attrs)
            (.. (tag tag-name attrs)
                (table.concat (icollect [_ element (ipairs body)]
                                (html element allow-no-escape?)) " ")
                "</" tag-name ">")))))