santoku-template
View on LuaRockscompile-once templates of text with embedded Lua blocks, the engine behind .tk file expansion in toku
santoku-template is a compile-once template engine. Text with embedded <% ... %> Lua blocks becomes a render function that runs each block in an environment you provide. It's the engine behind .tk file expansion in the toku build harness.
Details
- The API is four functions: compile, render, serialize_deps and deserialize_deps.
- Every block also gets three injected names: push, pop and showing.
- A block that returns a string emits that string.
- A block that returns nothing runs for its side effects and collapses the blank line it sits on.
- A push and pop stack gates regions of output.
- The build harness renders nginx confs, index.html, service workers and Lua sources against the project configuration before bundling.
- The string-based examples run in the page. The file-based and build-harness examples need a filesystem, so they're shown for reading.
The engine
Compile once, render many
compile(data, name) parses the template and returns a render function. Call that function with a fresh env each time.
local template = require("santoku.template")
local render = template.compile("<title><% return title %></title>")
print(render({ title = "Hello, World!" }))
return render({ title = "Second render" })
Details
- name labels errors, and defaults to "template".
- A block that fails to compile raises "Invalid Lua code in template" with name:line.
- To compile a file, read it yourself and pass its path as the name: compile(fs.readfile(fp), fp).
The entry points
render(data, env, global) compiles and calls in one step. Text without blocks passes through verbatim.
local template = require("santoku.template")
print(template.render("plain text passes through verbatim"))
local via_render = template.render("<h1><% return heading %></h1>", { heading = "Docs" })
local via_compile = template.compile("<h1><% return heading %></h1>")({ heading = "Docs" })
print(via_render)
return tostring(via_render == via_compile)
Details
- The module reads no files, so it loads without santoku.fs and runs in a browser page.
Environments and globals
Blocks resolve names from env first, then fall back to the global table you pass, often _G. The fallback sits on the __index chain of the env.
local template = require("santoku.template")
local arr = require("santoku.array")
print(template.render("<% return tostring(#word) %>", { word = "loud" }, _G))
return template.render("<% return arr.concat(names, ', ') %>", { arr = arr, names = { "ada", "grace" } }, _G)
A fresh environment per render
The render call copies env into a new table. Blocks share state within one render, but assignments never write back to your table and never leak into the next render.
local template = require("santoku.template")
local t = template.compile("<% n = n + 1 %><% return 'n is ' .. n %>")
local env = { n = 1 }
print(t(env))
print(t(env))
return "caller still sees n = " .. env.n
Block return values
A returned value must be a string, and anything else raises. A block with no return contributes only its side effects, which later blocks in the same render see.
local template = require("santoku.template")
print(template.render("count: <% return tostring(count) %>", { count = 3 }, _G))
return template.render("<% total = price * qty %>total: <% return tostring(total) %>",
{ price = 3, qty = 4 }, _G)
Details
- Convert numbers with tostring.
Loops with library helpers
Blocks are plain Lua, so a list renders through santoku.array passed in env. The spec of the library uses this exact pattern to emit repeated attributes.
local template = require("santoku.template")
local arr = require("santoku.array")
local t = template.compile(
"<ul><% return arr.concat(arr.map(items, function (x) return '<li>' .. x .. '</li>' end)) %></ul>")
return t({ arr = arr, items = { "one", "two", "three" } })
Gates with push and pop
push(cond) gates output until pop(). While the top of the stack is false, text and returned strings are dropped.
local template = require("santoku.template")
local t = template.compile("<% push(admin) %>[admin panel] <% pop() %>welcome")
print(t({ admin = true }))
return t({ admin = false })
Nested gates
push ANDs its condition with the current top, so an outer false gate silences everything inside it. showing() reads the current state from a block.
local template = require("santoku.template")
local t = template.compile("<% push(a) %>A<% push(b) %>B<% pop() %>a-tail<% pop() %>end")
print(t({ a = true, b = true }))
print(t({ a = true, b = false }))
return t({ a = false, b = true })
Blocks inside a false gate
A gate filters output only. Every block runs whatever the stack holds, so side effects made inside a false gate are visible afterward.
local template = require("santoku.template")
local arr = require("santoku.array")
local t = template.compile(arr.concat({
"<% push(false) %><% ran = true %>",
"<% return 'hidden' %><% pop() %>",
"<% return ran and 'the hidden block ran' or 'it did not run' %>",
}))
return t()
Whitespace collapsing
A block that returns nothing joins the blank line it would leave behind. The render also trims trailing whitespace after the final block.
local template = require("santoku.template")
local out = template.render("first\n<% skipped = true %>\nlast")
print(out == "first\nlast")
local trimmed = template.render("value: <% return 'x' %>\n ")
return "[" .. trimmed .. "]"
Compile and render errors
A block that isn't valid Lua raises during compile, before any render. A block that returns a non-string raises during render. santoku.error.pcall traps both.
local err = require("santoku.error")
local template = require("santoku.template")
local ok = err.pcall(function ()
return template.compile("<% if %>")
end)
print("bad block compiles:", ok)
local ok2 = err.pcall(function ()
return template.render("<% return 42 %>")
end)
print("number return renders:", ok2)
return tostring(ok) .. " " .. tostring(ok2)
Includes through env
The engine has no built-in include. Pass a render helper through env and call it from a block.
local template = require("santoku.template")
local pages = {
layout = "<html><% return render(pages.body) %></html>",
body = "<b><% return msg %></b>",
}
local env
env = {
pages = pages,
msg = "hello",
render = function (s)
return template.compile(s)(env)
end,
}
return template.compile(pages.layout)(env)
Files and include chains
Read the file with santoku.fs and compile it with its path as the name, so errors carry path:line. A renderfile helper of your own, which threads a shared env, nests templates across files.
local template = require("santoku.template")
local fs = require("santoku.fs")
local title = "test/res/template/title.html"
print(template.compile(fs.readfile(title), title)({ title = "Hello, World!" }))
local env
local function renderfile (fp)
return template.compile(fs.readfile(fp), fp)(env, _G)
end
env = { renderfile = renderfile, title = "Hello, World!" }
return template.render("<% return renderfile('test/res/template/index.html') %>", env)
Details
- santoku-template 3.0.0 dropped compilefile and renderfile.
- The index -> body -> body-content fixtures of the library nest this way.
Makefile-style dependency rules
serialize_deps(source, dest, deps) emits one make rule, source: deps, from a dep set the caller recorded. deserialize_deps reads the first line back into a set.
local template = require("santoku.template")
local arr = require("santoku.array")
print(template.serialize_deps("index.html.tk", "index.568b57e86a93.html", { ["res/header.html"] = true }))
local deps = template.deserialize_deps("index.html.tk: res/header.html res/footer.html")
local names = {}
for name in pairs(deps) do
names[#names + 1] = name
end
arr.sort(names)
return arr.concat(names, ", ")
Details
- dest must be a string, but it doesn't appear in the output.
- Dep order follows table iteration.
In the build harness
.tk file expansion
toku templates any file with .tk in its name and strips the .tk from the destination. The harness renders the file against the project env, then writes the output and a one-line .d rule beside it.
local template = require("santoku.template")
local fs = require("santoku.fs")
local env = { client = { verbose = false }, readfile = fs.readfile }
local fp = "client/lib/tasks/main.tk.lua"
local out = template.compile(fs.readfile(fp), fp)(env, _G)
fs.writefile("client/lib/tasks/main.lua", out)
Details
- rules.copy, rules.exclude and rules.template override the default.
- The env adds depend and a readfile that records dependencies.
- That step is add_file_target in santoku.make.common.
- At its core is one compile and render of the text of the file.
Config values into Lua source
A .tk.lua file bakes project configuration into the shipped module. Interpolation like this is for values.
<% str = require("santoku.string") %>return {
name = <% return str.format("%q", name) %>,
version = <% return str.format("%q", version) %>,
verbose = <% return tostring(client.verbose or false) %>,
}
Details
- toku web projects hand every template an env that carries name, version, client, server, nginx, component, target, dist_dir, work_dir, hashed, readfile and depend.
- A server template gets no environment value. A page's lib rock renders with environment set to main.
- To leave code out of a build entirely, gate it with push and pop.
- A rendered runtime condition still compiles the dead branch, and everything inside it, into the output.
An nginx conf template
A server/nginx.tk.conf can be one block. It resolves content-hashed filenames with the hashed helper of the build, then hands a mustache conf source to santoku.mustache against a context table.
<%
local arr = require("santoku.array")
local ctx = nginx
ctx.index_hashed = hashed("index.568b57e86a93.html")
ctx.common_js_hashed = hashed("common.js")
local env_lines = {}
for k in pairs((server or {}).run_env_vars or {}) do
env_lines[#env_lines + 1] = "env " .. k .. ";"
end
ctx.nginx_env_lines = arr.concat(env_lines, "\n")
return require("santoku.mustache")(readfile("res/nginx.conf"))(ctx)
%>
Details
- Before the handoff, it writes an env directive for each server.run_env_vars name. nginx workers then keep the variables that the run.sh of the server exports.
- The harness records the readfile calls of the block as dependencies, so the conf rebuilds when that source changes.
A PWA index.html template
A static/index.tk.html builds the page with the santoku.web.pwa helpers: hashed asset links and the shared index builder over client.pwa config.
<%
local tbl = require("santoku.table")
local index = require("santoku.web.pwa.index")
return index(tbl.merge({
manifest = "/" .. hashed("manifest.26e55a5b2d51.json"),
favicon_svg = "/" .. hashed("favicon.f18d929ffecd.svg"),
}, client.pwa, {
title = "Example App",
sw = "/sw.js",
head = '<link rel="stylesheet" href="/' .. hashed("index.49e48e032508.css") .. '">',
csp = true,
}))
%>
Details
- csp = true makes index compute a CSP meta tag from the script hashes of the finished markup.
- The santoku-web tab covers the options of the builder: https://santoku.dev/santoku-web
santoku-make as a template
The web project module of santoku-make is itself a .tk.lua file. When the engine builds, blocks inline its shell and config resources as base64 string constants.
add_templated_target_base64(server_dir(base_server_run_sh),
<% return str.quote(str.to_base64(readfile("res/web/run.sh"))) %>, server_env)
add_templated_target_base64(server_dir(base_server_luarocks_cfg),
<% return str.quote(str.to_base64(readfile("res/web/luarocks.lua"))) %>, server_env)
Details
- At project build time, add_templated_target_base64 decodes those constants and renders them against the project env.
.tk names in web projects
The names available inside <% %> depend on which environment renders the file. The code lists the names that web projects inject.
readfile(path)
depend(path, prune)
root_dir
hashed(name)
version
client, nginx
openresty_dir
lua_package_path
lua_package_cpath
dist_dir, public_dir
var(name)
public_files
registered_public_files
public_files_static_for_precache
Details
- readfile and root_dir let a template pull in a sibling file. That's how a small .tk.conf renders a large template kept in res.
- hashed maps a logical asset name to its content-hashed filename. It's the correct way to reference an asset from a template.
- In server/nginx.tk.conf, nginx is the render context. There, nginx.nginx is the nginx block of your descriptor merged with the daemon, pid and log settings.
- That's why the scaffold opens with <% n = nginx.nginx %>.
- In every other template, nginx is the block of the descriptor itself.
- .tk expansion applies to every file in an environment, including test/spec. So a spec may be a template and embed build-time data the same way a source file can.
| Name | Value |
|---|---|
| readfile(path) | reads a file relative to the project root |
| depend(path, prune) | records a file or directory tree as a dependency without reading it, and returns path |
| root_dir | the absolute project root |
| hashed(name) | a deferred token resolved after hashing, and the final name in server/nginx.tk.conf |
| version | the version from the descriptor |
| client, nginx | the client and nginx blocks of the descriptor |
| openresty_dir | the resolved OpenResty installation |
| lua_package_path, lua_package_cpath | point at the private rock tree of this environment |
| dist_dir, public_dir | the output directories of this environment |
| var(name) | reads variable_prefix .. "_" .. name, such as TK_MYAPP_DEBUG |
| public_files | every public file: static files, pages and their .wasm |
| registered_public_files | client.public as a set |
| public_files_static_for_precache | the static files eligible for precaching |