santoku-web: templates
View on LuaRocksmustache templates compiled at build time, rendered as live DOM with keyed lists, and loaded from a template folder for app.define and the server
santoku-web's templates: santoku.mustache source compiled at build time, rendered as live DOM that updates in place, and loaded from a template folder for app.define and the server.
Details
- The rest of santoku-web is on its own tab: https://santoku.dev/santoku-web
Apps and templates
Templates compiled at build time since santoku-web 4.0.0
santoku.web.mustache renders santoku.mustache templates as live DOM that updates in place. compile(name, source, opts) runs at build time, inside a .tk.lua file the client requires.
local compile = require("santoku.web.mustache.compile")
local err = require("santoku.error")
local arr = require("santoku.array")
local c = compile("list", "<ul>{{#items}}<li data-key=\"{{id}}\">{{name}}</li>{{/items}}</ul>")
local names = {}
for name in pairs(c) do names[#names + 1] = name end
arr.sort(names)
print(arr.concat(names, " "))
print(c.list.html)
print(err.pcall(compile, "t", "<div class={{c}}>x</div>"))
print(err.pcall(compile, "t", "<p><div></div></p>"))
print(err.pcall(compile, "t", "<b>\n{{> row}}</b>", { partials = {} }))
return c.list.html
Details
- The .tk.lua file returns serialize(compiled, true), so the page ships the compiled tables and never the compiler.
- Since santoku-web 9.0.0, compile returns a table keyed by template name: name itself and each partial it reaches, compiled once. A section that holds markup nests its template in its hole.
- A section that holds only text folds into its text node.
- opts.partials maps a partial's name to its source. Each {{> x}} becomes a marker the runtime fills with x, rendered with the same context. A partial sits only between elements, and a partial may include itself.
- compile strips the common indentation of the source and each partial unless opts.dedent is false.
- Mustache comments drop, HTML comments stay, and standalone tag lines follow the mustache spec.
- The specs check the DOM against santoku.mustache's output for the same template and data.
- compile raises for anything the live DOM couldn't reproduce. The error is "santoku.web.mustache", a location such as "t line 2" or "row line 2" for a partial, and a message from the tables.
- Since santoku-web 4.1.0, a {{{x}}} beside elements compiles to a pair of empty comments with the raw HTML between them.
| Mustache syntax error |
|---|
| "unclosed mustache tag" |
| "delimiter changes are unsupported" |
| "colon tags ({{:x}}) are unsupported" |
| "{{{ without a closing }}}" |
| "empty mustache tag" |
| "{{x}} uses a mustach extension (guards, object iteration, escapes or json pointers)" |
| "{{x}} has an empty name segment" |
| "{{#x}} is never closed" |
| "{{/x}} closes no section" |
| "{{/x}} closes {{#y}} from line N" |
| "partial x is not in the partials table" |
| "{{> x}} inside <tag>: a partial sits only between elements" |
| "the template holds control bytes 1 or 2" |
| Parser rewrite error |
|---|
| "<x> inside <y>: the parser closes the <y> first", for <p>, <li>, <dd>, <dt> and <option> |
| "<h2> inside <h1>: the parser closes the heading first" |
| "<a> inside <a>: the parser closes the outer <a>" |
| "<optgroup> inside <optgroup>: the parser closes the outer one" |
| "<x> inside <x>", for button, form and select |
| "<tr> directly inside <table>: the parser adds a <tbody>; write it" |
| "<x> directly inside <y> is moved by the parser" |
| "<x> inside <select> is dropped or moved by the parser" |
| "<x> inside <y> is dropped by the parser" |
| "text directly inside <x> is moved out of the table by the parser" |
| "{{x}} directly inside <y>", for table elements |
| "<x> inside <svg> or <math> breaks out of foreign content" |
| "<x> is unsupported in a template", for html, head, body and the other document elements |
| "<x/> does not close in HTML; write <x></x>" |
| "</x> closes <y>; implicit end tags are unsupported" |
| "</x> closes no element" |
| "<x> is never closed" |
| Tag and attribute error |
|---|
| "mustache tag right after <" |
| "mustache tag inside a tag name" |
| "mustache tag inside </x>" |
| "{{x}} in an attribute name position of <y>" |
| "mustache tag inside an attribute name of <x>" |
| "quote the value of a in <x>: it holds mustache tags" |
| "unterminated attribute value in <x>" |
| "<x> is not terminated" |
| "</x is not terminated" |
| "{{/x}} inside <y> closes a section opened outside the tag" |
| "{{#x}} opened inside <y> is not closed before the tag ends" |
| "{{/x}} closes a section opened outside this ...", in an attribute value or a script or style body |
| "{{#x}} is not closed inside this ...", in an attribute value or a script or style body |
| "checked=\"...\" holds a mustache tag in <x>, so the checked property never clears: put the section around the attribute, as in {{#x}}checked{{/x}}", since santoku-web 4.1.0, for a checked attribute whose value holds a mustache tag, with no section around the attribute inside the tag. A selected attribute gets the same message with selected in place of checked. |
| Section, comment and keyed list error |
|---|
| "{{/x}} closes inside <y> but {{#x}} opened outside it" |
| "</x> closes while {{#y}} is open inside it" |
| "{{#x}} is not closed inside its element" |
| "unterminated HTML comment" |
| "mustache tags inside an HTML comment are unsupported" |
| "<! and <? declarations are unsupported" |
| "</ without a tag name is unsupported" |
| "mustache tags inside a nested <template> are unsupported" |
| "{{#x}}: data-key needs exactly one element at the top of the section" |
| "data-key must not sit inside a section in the tag" |
| "{{#x}}: data-key rows would differ in whitespace by position; put the section tags each on their own line, or both inline" |
| "{{#x}}: another data-key list already owns the field x" |
Live views and keyed lists since santoku-web 4.0.0
require("santoku.web.mustache")(dom, compiled) returns M. M.render(name, data, parent, before) clones a template, fills it from data, inserts it into parent ahead of before and returns a view.
local dom = require("santoku.web.dom")
local mustache = require("santoku.web.mustache")
local M = mustache(dom, require("myapp.templates"))
local data = {
title = "Todos", owner = "matt",
todos = { { id = "a", body = "milk", mine = true }, { id = "b", body = "eggs" } },
}
local view = M.render("todos", data, "app")
local todos = data.todos
todos.insert({ id = "c", body = "bread" }, "b")
todos.move("a")
todos.update("b", { id = "b", body = "eggs", done = true })
print(todos.len(), todos.get("b").done)
for key, row in todos.each() do print(key, row.body) end
data.owner = "sam"
view.update(data)
view.remove()
Details
- Since santoku-web 4.1.0, M mounts each compiled template as a dom template on that template's first render.
- view.update(data) rewrites only the text, attributes and sections whose output changed.
- view.remove() removes the nodes and releases every handle.
- A section shows for true, a non-zero number, a non-empty string or a non-empty table. An array repeats the section, and any other table becomes its context.
- When a value, checked or selected attribute changes, render sets the matching DOM property too.
- A model change resets the field, and an update that leaves the attribute alone keeps what the user typed.
- Since santoku-web 4.1.0, new rows go in first to last. So a list-built <select> with no selected option lands on its first option, as a parse of the same HTML does.
- Since santoku-web 4.1.0, a <select value="{{x}}"> sets its value property after the options inside it. So it shows x after the first render, even when a section builds the options.
- An update that changes anything inside the select sets the value again, so x still shows when only the options change.
- When x stays empty, an options change leaves the browser's own pick.
- An update that changes nothing inside the select keeps the user's choice. Row changes through the list object don't set the value again.
- A section whose one top element carries data-key is a keyed list. Rows diff by key, and a kept row moves without a rebuild.
- For a keyed section outside any section other than an inverted one, render replaces that field of data with a list object.
| List object method | Note |
|---|---|
| insert(row, before_key) | takes a plain table |
| remove(key) | removes the row with that key |
| move(key, before_key) | moves the row ahead of before_key |
| update(key, row) | takes a plain table, and can't change the row's data-key |
| get(key) | returns the row, or nil when no row has that key |
| len() | returns the row count |
| each() | yields each key and row in order |
- A missing before_key means the end.
- Since santoku-web 4.1.0, a list inside an inverted section gets a list object too. While that section is hidden, insert, remove, move and update change only the list's rows and touch no DOM.
- When the inverted section shows again, it renders those rows in order, and the field keeps the same list object.
- An unkeyed list field stays an array.
- Rows from get and each are read-only, nested tables included. A write raises "rows are read-only; replace the row with update(key, row)".
- An edit to a row table in place renders nothing, since update skips a list that's still the same object. Call update(key, row) instead.
- Assigning a new array to the field diffs it by key into the same list object, and nil or {} empties it.
- A row reads a field it lacks from the parent data. view.update refreshes that row only when the parent field changes.
- Since santoku-web 4.1.0, a dotted name such as {{rpt.preselect}} counts as its full path. So a row refreshes when rpt.preselect changes, even in place, and not when another field of rpt does.
- A section such as {{#rpt}}{{preselect}}{{/rpt}} inside a row still counts only rpt.
| Errors from the list object and render |
|---|
| "duplicate data-key" |
| "no row with data-key" |
| "row moved before itself" |
| "update changes the row's data-key" |
| "insert takes a plain table" |
| "update takes a plain table" |
| "unknown template" |
| "lambdas are unsupported", for a function value |
Build-time templates
Template directory loader since santoku-web 4.2.0
loader.read(dir, opts) reads every file under a template directory into a table keyed by dotted path. client and server then precompile the templates a page names, with every partial they include.
local loader = require("santoku.web.mustache.loader")
local str = require("santoku.string")
local tpl = loader.read("res/templates", {
readfile = readfile,
transforms = {
html = function (text)
return (str.gsub(text, "^<!%-%-.-%-%->\n", ""))
end,
},
})
local client_src = loader.client(tpl, { "search.html" })
local templates_src = loader.templates("res/templates/components", { readfile = readfile })
local server_src = loader.server(tpl, { "page.html" })
local page = loader.render(tpl, { "page.html" })["page.html"]
print(page({ title = "hello" }))
Details
- Keys keep the file extension: rows/row.html becomes rows.row.html, and a template includes it as {{>rows.row.html}}.
- opts.transforms maps an extension such as html to fn(text, path), which rewrites each file before the loader stores it. path is relative to dir, such as rows/row.html.
- opts.readfile replaces fs.readfile. A .tk file passes its own readfile, so the build rebuilds when a template changes.
- closure(tpl, names) returns the named templates and every partial they reach. A missing one raises "santoku.web.mustache.loader: no template" and the name.
- client(tpl, names) returns the source of a client .tk.lua module: each name compiled by santoku.web.mustache.compile, merged and serialized.
- server(tpl, names) returns Lua source that compiles the templates with santoku.mustache when it loads, so the server needs no santoku-web. With no names it takes the whole directory.
- render(tpl, names) loads that source in process and returns the render functions, for a build step that writes static pages.
- Since santoku-web 9.0.0, templates(dir, opts) reads the folder dir and returns the source of a table with one entry, { name, compiled, style }, per html file that nothing includes. A file that some {{> }} names gets no entry, and each partial compiles once in the shared table.
- opts.readfile and opts.transforms go to read. opts.with is a table of extra templates keyed like read's output, merged in before compile, such as closure(read(dir2), names). A with file nothing includes becomes an entry too.
- An entry's name is its key without .html, with each ., / and - turned into _: job-search.html is job_search and admin/tools.html is admin_tools. An entry's <style> block becomes entry.style, and a partial keeps its <style> in its body.
- Every template compiles with compile's default dedent. templates raises on a name that isn't a Lua name, on two files with one name, and when no html file is left.
- The loader runs where santoku-fs runs: a build, a server or a CLI, never a page.