-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtmlgen.lua
75 lines (73 loc) · 1.6 KB
/
htmlgen.lua
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
local function htmlgen(wrt)
wrt = wrt or Write
local gsub, format = string.gsub, string.format
local select, setmetatable = select, setmetatable
local esc = EscapeHtml or function(s)
return (gsub(s, "[&><\"']", {
["&"]="&", [">"]=">",
["<"]="<", ["\""]=""",
["'"]="'",
}))
end
local function writeattr(t, off)
while off <= #t do
if type(t[off]) == "table" then
writeattr(t[off], 1)
off = off + 1
else
wrt(" "..t[off])
off = off + 1
if t[off] then
wrt("=\""..esc(t[off]).."\"")
off = off + 1
end
end
end
for k, v in pairs(t) do
if type(k) == "string" then
wrt(" "..k)
if v then
wrt("=\""..esc(v).."\"")
end
end
end
end
local mt = {
__call = function(self, arg)
return self
end,
__close = function(self)
wrt("</"..self.tag..">")
end,
}
return setmetatable({
doc = function() wrt"<!DOCTYPE html>" end,
text = function(self, text, ...)
if select("#", ...) > 0 then
text = format(text, ...)
end
wrt(esc(text))
end,
raw = function(self, raw, ...)
if select("#", ...) > 0 then
raw = format(raw, ...)
end
wrt(raw)
end,
}, {
__call = function(self, tag)
local t
if type(tag) == "table" then
t = tag
tag = tag[1]
end
wrt("<"..tag)
if t then
writeattr(t, 2)
end
wrt">"
return setmetatable({tag=tag, close=mt.__close}, mt)
end,
})
end
return htmlgen