Index

resty-gitweb / master

A git web interface for Lua/OpenResty (you're on it right now!)

Latest Commit

{#}TimeHashSubjectAuthor#(+)(-)GPG?
1224 Jan 2021 17:05dda0daeNew HTML generatorJosh Stockin16319G

Blob @ resty-gitweb / utils / builder.lua

text/plain1926 bytesdownload raw
1-- resty-gitweb@utils/builder.lua
2-- XML (HTML, Atom, RSS) builder class
3
4-- Copyright (c) 2020 Joshua 'joshuas3' Stockin
5-- <https://git.joshstock.in/resty-gitweb>
6-- This software is licensed under the MIT License.
7
8local builder = {}
9
10builder.__index = function(t, k)
11 if builder[k] then return builder[k] end
12 return builder.createobject({}, k)
13end
14
15builder.__call = function(self, opts)
16 for i,v in pairs(opts) do
17 if type(i) ~= "number" then
18 self._attributes[i] = v
19 else
20 table.insert(self._objects, v)
21 end
22 end
23 return self
24end
25
26function builder.createobject(attr, tag)
27 local o = {}
28 o._type = "object"
29 o._tag = tag
30 o._attributes = attr or {}
31 o._objects = {}
32 setmetatable(o, builder)
33 return o
34end
35
36function builder:new(doctype)
37 local o = {}
38 o._type = "root"
39 o._doctype = doctype
40 o._objects = {}
41 setmetatable(o, self)
42 return o
43end
44
45function builder:build()
46 local str = ""
47 if self._type == "root" then
48 if self._doctype:lower() == "html" then
49 str = str .. "<!DOCTYPE html>\n"
50 end
51 end
52 if self._type == "object" then
53 if self._tag then
54 str = str .. "<" .. self._tag
55 end
56 for i,v in pairs(self._attributes) do
57 if i:sub(1,1) ~= "_" then
58 str = str .. " " .. i .. "=\"" .. tostring(v) .. "\""
59 end
60 end
61 str = str .. ">"
62 end
63 if self._type == "object" or self._type == "root" then
64 for _,v in pairs(self._objects) do
65 if type(v) == "table" then
66 str = str .. v:build()
67 else
68 str = str .. v
69 end
70 end
71 end
72 if self._type == "object" then
73 if self._attributes._closetag ~= false then
74 str = str .. "</" .. self._tag .. ">"
75 end
76 end
77 return str
78end
79
80return builder
81