html.lua/html.0.2.lua
2022-05-03 19:16:41 -03:00

84 lines
1.8 KiB
Lua

function map(list, func)
local new_list = {}
for key, value in pairs(list) do
new_list[key] = func(key, value)
end
return new_list
end
function join(list)
local string = ""
for key, value in pairs(list) do
string = string .. value
end
return string
end
function render(element)
if type(element) == "string" then
-- TODO: escape
return element
end
if element[1] then
return join(map(element, function(key, value)
return render(value)
end))
end
local close_tag = "</"..element.type..">"
local self_closing = element.type == "meta"
if self_closing then
close_tag = ""
end
return "<"..element.type
..join(map(element.parameters, function(key, value)
-- TODO: escape
return " "..key.."='"..value.."'"
end))
..">"
..join(map(element.children, function(key, value)
return render(value)
end))
..close_tag
end
local function basic_element(name)
return function(params, children)
return { type = name, parameters = params, children = children }
end
end
function a(params, children)
if not params.href then
print("WARNING: Link `"..join(children).."` doesn't have a href.")
end
return basic_element("a")(params, children)
end
head = basic_element("head")
body = basic_element("body")
title = basic_element("title")
h1 = basic_element("h1")
h2 = basic_element("h2")
h3 = basic_element("h3")
h4 = basic_element("h4")
h5 = basic_element("h5")
h6 = basic_element("h6")
ul = basic_element("ul")
ol = basic_element("ol")
li = basic_element("li")
p = basic_element("p")
meta = basic_element("meta")
local link = a({ href = "https://nulo.in" }, {"Hola, soy html.lua"})
local head_block = head({}, {
meta({charset = "utf-8"}, {}),
title({}, {"Hello world"}),
})
local body_block = body({}, {
link
})
--print(render(head_block)..render(body_block))