-
Notifications
You must be signed in to change notification settings - Fork 126
html
Phil Hagelberg edited this page Mar 18, 2022
·
1 revision
There is a simple module in the fennel-lang.org codebase for generating HTML from tables.
;; A *very* basic HTML generation library.
;; Basic escaping features only; never use this on user input!
(local entity-replacements {"&" "&" ; must be first!
"<" "<"
">" ">"
"\"" """})
(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]
(.. (tag tag-name attrs)
(table.concat (icollect [_ element (ipairs body)]
(html element allow-no-escape?)) " ")
"</" tag-name ">"))))
Some example usage:
(local html (require :html))
(local out [:html {:lang "en"}
[:head {}
[:meta {:charset "UTF-8"}]
[:link {:rel "stylesheet" :href "/fennel.css"}]
[:link {:rel "stylesheet"
:href "https://code.cdn.mozilla.net/fonts/fira.css"}]
[:title {} "the Fennel programming language survey"]]
[:body {}
[:h1 {} "The Fennel Survey"]
[:hr {}]
[:p {} "The survey is closed now; thanks for participating!"
"You can see" [:a {:href "2021"} "the results"] "now."]]])
(print (html out))