From 9c4a7fd604eafb716e9162fded33a151bd2fb515 Mon Sep 17 00:00:00 2001 From: unwox Date: Thu, 6 Jun 2024 16:08:54 +0600 Subject: simple fennel setup --- html.fnl | 31 +++++++++++++++++++++++++++++++ init.fnl | 24 ++++++++++++++++-------- 2 files changed, 47 insertions(+), 8 deletions(-) create mode 100644 html.fnl diff --git a/html.fnl b/html.fnl new file mode 100644 index 0000000..689f416 --- /dev/null +++ b/html.fnl @@ -0,0 +1,31 @@ +(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 render [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)] + (render element allow-no-escape?)) " ") + "")))) + +{ :render render } diff --git a/init.fnl b/init.fnl index f14817e..bce021a 100644 --- a/init.fnl +++ b/init.fnl @@ -1,9 +1,17 @@ (local fennel (require :fennel)) -{ - :routes { - :/ (fn [method path headers body] - (values 200 { :content-type "applicaton/json" } - "{ \"test\": 123 }")) - ; :/test (fn [] "test?") - } -} +(local html (require :html)) + +(local template + [:html {:lang "en"} + [:head {} + [:meta {:charset "UTF-8"}] + [:title {} "A new cool web server for lua"]] + [:body {} + [:h1 {} "Hello!"] + [:pre {} "This is my super blog!"]]]) + +(fn root-handler [method path headers body] + (let [headers { :content-type "text/html" }] + (values 200 headers (html.render template)))) + +{ :routes { :/ root-handler } } -- cgit v1.2.3