~aleteoryx/lfm_embed

ref: d7727c21586734f19d016fc84f94eaf0764eda34 lfm_embed/src/theming/lua-lib/html.lua -rw-r--r-- 1.0 KiB
d7727c21alyx html.lua functional 7 months ago
                                                                                
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
-- SPDX-License-Identifier: AGPL-3.0-only

local function html_escape(s)
  expect(1, s, "string")

  s = string.gsub(s, "&", "&")
  s = string.gsub(s, "<", "&lt;")
  s = string.gsub(s, ">", "&gt;")
  s = string.gsub(s, "'", "&#39;")
  s = string.gsub(s, "\"", "&quot;")

  return s
end

local function html(el, tbl)
  expect(1, el, "string")
  expect(2, tbl, "table")

  innerHtml = ""
  attributes = ""

  for k, v in pairs(tbl) do
    if type(k) == "string" then
      expect.field(tbl, k, "string")
      attributes = attributes .. " " .. k .. "='" .. html_escape(v) .. "'"
    end
  end
  for k, v in ipairs(tbl) do
    expect.field(tbl, k, "string", "table")
    if type(v) == "table" then v = html_escape(v[1]) end
    innerHtml = innerHtml .. v
  end

  return string.format("<%s%s>%s</%s>", el, attributes, innerHtml, el)
end

local function root(tbl)
  return "<!DOCTYPE html>\n" .. html("html", tbl)
end

return setmetatable(
  { root    = root },
  { __call  = html,
    __index = function (idx) return function(tbl) html(idx, tbl) end end })