simple HTML DSL for lua 5.3
this library returns a table which, when indexed with the name of an HTML tag, provides a function which generates a data structure representing an HTML element. when this data structure is converted to a string, the corresponding HTML is generated.
local h = require "html"
calling a tag's function with no arguments produces a self-closing tag.
source
print(h.hr())
output
<hr />
calling a tag's function with a single array or value argument produces a tag with the children provided in the array. non-table values may appear in the list of children or in its stead. they are converted to a string an escaped.
source
print(h.section{h.h1"foo",h.p"bar"})
output
<section><h1>foo</h1><p>bar</p></section>
calling a tag's function with a single set of key/value pairs as the argument produces a self-closing tag with attributes corresponding to the key/value pairs
source
print(h.meta{charset = "utf-8"})
output
<meta charset="utf-8" />
calling a tag's function with a set of key/value pairs and then an array or value as the arguments produces a tag with attributes corresponding to the key/value pairs.
source
print(h.a({href = "https://example.com"}, "foobar"))
output
<a href="https://example.com">foobar</a>
a table used in a list of children must either be generated from the HTML functions or have a tohtml
function or a render
function, returning HTML structures or HTML source respectively. a table that is not a set of attributes or an array of element children may not be used as arguments to an HTML function.
source
local db_record = {name = "foobar", id = 256}
setmetatable(db_record, {
tohtml = function(x)
return h.a(
{href = "https://example.com/" .. x.id}, x.name)
end
})
print(h.p{"search result: ", db_record})
output
<p>search result: <a href="https://example.com/256">foobar</a></p>
the raw
function will insert text verbatim into the HTML, unescaped.
source
local html_source = "<marquee>hello</marquee>"
print(h.p{html_source})
print(h.p{h.raw(html_source)})
output
<p><marquee>hello</marquee></p>
<p><marquee>hello</marquee></p>
included with this documentation is example.lua
which produces this documenation in HTML via the DSL.