santoku-mustache
View on LuaRocksmustache template rendering in C: compile once, render Lua values to strings, with sections, partials, and dedent
santoku-mustache is the framework's runtime template renderer. It renders Mustache templates against plain Lua values. The module is one function, which compiles a template and returns a render closure, and the closure returns a string. toku web projects use it for HTML template packs and generated config.
Details
- santoku.mustache is a single C module over the vendored mustach 1.2.10 library, with every extension on.
- Compile takes optional partials and dedents the template by default.
- The render closure takes a table, a number, a boolean or nil.
- Core Mustache covers variables, dotted paths, sections, inversion, iteration, partials, comments and custom delimiters.
- The extensions add equality and comparison guards on tag names, object iteration with {{*}}, and escaped-dot and JSON pointer syntax for awkward keys.
- santoku-template is a different engine. It expands <% ... %> Lua blocks at build time: https://santoku.dev/santoku-template
Compile and render
mch(template) compiles a template and returns a closure that renders it against a context. A variable reads a key, dot notation reads a nested table, and a missing key renders empty.
local mch = require("santoku.mustache")
local render = mch("{{greeting}} {{target}}")
print(render({ greeting = "hello", target = "world" }))
print(mch("{{a.b.c}}")({ a = { b = { c = "value" } } }))
print("missing renders empty:", "[" .. mch("{{missing}}")({}) .. "]")
print(mch("{{num}} {{flag}}")({ num = 42, flag = true }))
print(mch("{{a}} {{b}}")({ a = 2.5, b = 1e15 }))
return render({ greeting = "goodbye", target = "moon" })
Details
- Numbers format through %.14g.
- Booleans render as true or false.
- The closure captures the template at compile time.
Scalar contexts
The root context can be a number, a boolean or nil instead of a table. {{.}} reaches the root, and a section tests it. A string isn't a valid root.
local mch = require("santoku.mustache")
local dot = mch("{{.}}")
print(dot(42))
print(dot(true))
print("nil root:", "[" .. dot(nil) .. "]")
print(mch("{{#.}}yes{{/.}}")(true))
print(mch("{{^.}}no{{/.}}")(false))
return mch("{{.}} bottles")(99)
Sections and truthiness
A section renders only for a truthy value, under Lua-flavored rules. nil, false, 0, the empty string and the empty table are falsy. Everything else is truthy, a single space included.
local mch = require("santoku.mustache")
local sec = mch("{{#show}}yes{{/show}}{{^show}}no{{/show}}")
print("true:", sec({ show = true }))
print("false:", sec({ show = false }))
print("zero:", sec({ show = 0 }))
print("empty string:", sec({ show = "" }))
print("empty table:", sec({ show = {} }))
print("space:", sec({ show = " " }))
return sec({ show = "truthy" })
Inverted sections as fallbacks
A section paired with its inversion is the idiomatic default-value pattern. It renders the value when present and a literal otherwise.
local mch = require("santoku.mustache")
local host = mch("{{#host}}{{.}}{{/host}}{{^host}}localhost{{/host}}")
print(host({ host = "db1.internal" }))
print(host({}))
local flag = mch("{{^quiet}}verbose logging on{{/quiet}}")
print(flag({}))
return flag({ quiet = true })
Array iteration
A contiguous array-like table repeats its section once per element. {{.}} is the element itself, and field tags read from element records.
local mch = require("santoku.mustache")
print(mch("{{#items}}{{.}} {{/items}}")({ items = { 1, 2, 3 } }))
print(mch("{{#items}}{{.}}{{/items}}")({ items = {} }))
local rows = mch("{{#items}}{{name}}={{val}};{{/items}}")
return rows({ items = {
{ name = "a", val = 1 },
{ name = "b", val = 2 },
} })
The scope chain
Inside a section, a bare name walks outward through every enclosing scope until one scope has the key.
local mch = require("santoku.mustache")
local ctx = { top = "T", name = "outer", child = { name = "inner" } }
print(mch("{{name}}-{{#child}}{{name}}{{/child}}")(ctx))
print(mch("{{#child}}{{top}}/{{name}}{{/child}}")(ctx))
print("no chain for dots:", "[" .. mch("{{child.top}}")(ctx) .. "]")
return mch("{{child.name}}")(ctx)
Details
- A dotted path is stricter. Only its first key uses the chain, and the rest must resolve directly.
Scalar and nested sections
A section over a truthy scalar exposes the scalar as {{.}}. {{#.}} re-enters the current item, so a section walks a matrix without names.
local mch = require("santoku.mustache")
print(mch("{{#n}}n is {{.}}{{/n}}")({ n = 5 }))
print(mch("{{#rows}}{{#.}}{{.}}{{/.}}|{{/rows}}")({
rows = { { 1, 2 }, { 3, 4 } },
}))
return mch("{{#word}}[{{.}}]{{/word}}")({ word = "hi" })
Arrays and plain tables
Iteration needs integer keys 1..n with no gaps. A sparse or mixed table enters its section once instead, as a plain object scope.
local mch = require("santoku.mustache")
print(mch("{{#items}}x {{/items}}")({ items = { 1, 2, 3 } }))
local sparse = { 1, 2, 3 }
sparse[5] = 9
print(mch("{{#items}}x {{/items}}")({ items = sparse }))
local mixed = { "a", "b", label = "tagged" }
print(mch("{{#m}}{{label}}{{/m}}")({ m = mixed }))
return "[" .. mch("{{t}}")({ t = { 1, 2 } }) .. "]"
Details
- A table interpolated as a value renders empty.
Object iteration
Append .* to a section name to iterate a table's key-value pairs. {{*}} is the current key, {{.}} is the value, and record fields resolve normally.
local mch = require("santoku.mustache")
print(mch("{{#config.*}}{{*}}={{.}}{{/config.*}}")({
config = { host = "localhost" },
}))
print(mch("{{#users.*}}{{*}}:{{name}}{{/users.*}}")({
users = { u1 = { name = "Ada" } },
}))
return mch("{{#*}}{{*}}={{.}};{{/*}}")({ greeting = "hello" })
Details
- A bare {{#*}} iterates the root.
- The order follows Lua's pairs, so it's unspecified for a table with more than one key.
HTML escaping
Double braces escape exactly four characters: <, >, & and the double quote. Triple braces and the ampersand form, {{&name}}, emit the value raw.
local mch = require("santoku.mustache")
print(mch("{{h}}")({ h = "<b>" }))
print(mch("{{{h}}}")({ h = "<b>" }))
print(mch("{{&h}}")({ h = "<b>" }))
print(mch("{{q}}")({ q = "\"a\" & 'b'" }))
return mch("<span>{{{icon}}}</span>")({
icon = "<svg viewBox=\"0 0 24 24\"></svg>",
})
Details
- Single quotes pass through unescaped.
Comments and custom delimiters
{{! ... }} emits nothing. {{=open close=}} swaps the delimiter pair for the rest of the template, for an output format that uses braces itself.
local mch = require("santoku.mustache")
print(mch("a{{! hidden note }}b")({}))
local alt = mch("{{=<% %>=}}<% name %> and <%# on %>a section<%/ on %>")
print(alt({ name = "world", on = true }))
return mch("{{=[ ]=}}[greeting]")({ greeting = "hi" })
Details
- Each delimiter is up to 8 characters.
Awkward key names
A backslash-escaped dot keeps a literal dot inside one key. A leading colon takes the rest of the tag verbatim.
local mch = require("santoku.mustache")
local ctx = { a = { b = "nested" }, ["a.b"] = "flat" }
print(mch("{{a.b}}")(ctx))
print(mch("{{a\\.b}}")(ctx))
print(mch("{{:#tag}}")({ ["#tag"] = "hash key" }))
print(mch("{{:/server/host}}")({ server = { host = "db1" } }))
return mch("{{:/a.b}}")(ctx)
Details
- A colon plus slash switches to JSON pointer syntax. Slashes separate keys, and dots are literal.
Equality guards
{{#name=value}} enters only when the selected value equals the literal. {{#name=!value}} enters only when the value differs.
local mch = require("santoku.mustache")
local guard = mch("{{#env=prod}}PROD{{/env=prod}}{{#env=!prod}}NOT PROD{{/env=!prod}}")
print(guard({ env = "prod" }))
print(guard({ env = "dev" }))
print(mch("{{#n=42}}the answer{{/n=42}}")({ n = 42 }))
print(mch("{{#ok=true}}enabled{{/ok=true}}")({ ok = true }))
return mch("{{env=prod}}")({ env = "prod" })
Details
- Numbers compare numerically.
- Booleans compare as true or false.
- The same guard on a value tag renders the value conditionally.
Comparison guards
A section can compare with <, >, <= and >=. Numbers compare numerically, parsed from the literal, and strings compare byte-wise.
local mch = require("santoku.mustache")
local size = mch("{{#n>=10}}big{{/n>=10}}{{#n<10}}small{{/n<10}}")
print(size({ n = 42 }))
print(size({ n = 3 }))
print(mch("{{#price<=99.5}}deal{{/price<=99.5}}")({ price = 42.5 }))
return mch("{{#name>m}}late alphabet{{/name>m}}")({ name = "zed" })
Details
- The closing tag repeats the full guarded name.
Partials
opts.partials maps names to template strings or to compiled render closures. Partials come only from opts.partials.
local mch = require("santoku.mustache")
local item = mch("<li>{{.}}</li>")
local list = mch("{{#items}}{{>item}}{{/items}}", {
partials = { item = item },
})
print(list({ items = { 1, 2, 3 } }))
local wrap = mch("({{>inner}})", {
partials = { inner = "[{{val}}]" },
})
print(wrap({ val = "hello" }))
print("missing partial raises:", not (pcall(mch("a{{>nope}}b"), {})))
return mch("a{{#off}}{{>nope}}{{/off}}b")({ off = false })
Details
- For a closure, the module recovers the compiled template from the closure.
- Since santoku-mustache 2.3.1, a partial that the template names and opts.partials lacks raises "mustache render", "render failed", then NAME:LINE:COL: partial {{>x}} not found.
- The same error comes when opts.partials is absent, or when its value is neither a string nor a compiled template.
- The position is the {{>x}} tag in the template or partial that names it. NAME follows the rules in Render-time errors.
- Data values never stand in for partials, and no partial is read from a file.
- A partial inside a section that doesn't render is never looked up.
Dedent
Compile strips the shared indentation of nonblank lines and one leading newline. A long-string template can then sit indented in source.
local mch = require("santoku.mustache")
local tpl = mch([[
hello
world
]])
print(tpl({}))
print(mch("\nhello")({}))
local raw = mch("\n hello\n world\n", { dedent = false })
return raw({})
Details
- Pass dedent = false to keep the text verbatim.
- The leading newline goes even when no indentation is shared, so mch("\nhello") renders hello.
- santoku-mustache 2.2.2 and later strip that newline.
Render-time errors
Compile only dedents and captures the template, and parsing happens at each render. So a malformed template or a bad root raises when the closure is called.
local mch = require("santoku.mustache")
local render = mch("{{x}}")
print(render({ x = 1 }, "extra args ignored"))
print("string root:", (pcall(render, "nope")))
local unclosed = mch("{{#a}}never closed")
print("compiles, fails on render:", (pcall(unclosed, { a = true })))
return "errors surface at render time"
Details
- A bad root is anything other than a table, a number, a boolean or nil.
- The closure ignores arguments after the context.
- Since santoku-mustache 2.3.0, opts.name names the template in errors. A name that isn't a string raises at compile.
- A template error raises "mustache render", "render failed" and a detail of the form NAME:LINE:COL: MESSAGE. LINE and COL are 1-based, count bytes, and point into the string you passed in, before dedent.
- NAME is opts.name, or "template" without one. For an error inside a partial it is the partial's own name, or its key in opts.partials.
- Messages with a position: close tag {{/b}} doesn't match open tag {{#a}} at LINE:COL; close tag {{/a}} has no open section; section {{#a}} isn't closed; tag {{a has no closing }}; bad delimiter tag; unescaped tag {{{a}} has no closing }; a tag longer than 4096 bytes; a section nested deeper than 256.
- Errors that mustach raises while rendering carry no position and read NAME: MESSAGE, with the last partial loaded when there is one.
- Since santoku-web 12.0.1, the server templates that santoku.web.mustache.loader builds pass each template's key as its name.
An nginx server block
santoku server projects render their nginx conf from a context table. The template iterates location blocks and falls back on defaults.
local mch = require("santoku.mustache")
local conf = mch([[
server {
listen {{port}};
server_name {{domain}};
worker_connections {{#workers}}{{.}}{{/workers}}{{^workers}}512{{/workers}};
{{#locations}}
location {{path}} {
proxy_pass {{upstream}};
}
{{/locations}}
}
]])
return conf({
port = 8080,
domain = "docs.example.com",
locations = {
{ path = "/api", upstream = "http://127.0.0.1:9001" },
{ path = "/", upstream = "http://127.0.0.1:9000" },
},
})
The nginx pipeline
A server/nginx.tk.conf is a santoku-template block that the build harness expands. One way to write it computes hashed asset names, then renders a mustache conf source with the project config as context.
<%
local arr = require("santoku.array")
local ctx = nginx
ctx.context_path = (client and client.context_path) or ""
ctx.index_hashed = hashed("index.568b57e86a93.html")
ctx.common_js_hashed = hashed("common.js")
local env_lines = {}
for _, k in ipairs((server or {}).nginx_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
- Such a conf reaches nested config with dotted paths like {{nginx.port}} and {{nginx.error_log}}.
- Escaped dots, as in {{hosts.api\.example\.com}}, index a table whose keys contain dots.
Template packs
The loader below reads every file under res/web/templates and keys it by dotted path. It compiles each file with the whole set as its partials table, so any template can include any sibling with {{>path.name}}.
local fs = require("santoku.fs")
local str = require("santoku.string")
local mch = require("santoku.mustache")
local serialize = require("santoku.serialize")
return function (readfile, root_dir, runtime)
local tpl_dir = fs.join(root_dir, "res/web/templates")
local tpl = {}
for path, tp in fs.files(tpl_dir, true) do
if tp == "file" then
local key = str.match(path, "^.*/res/web/templates/(.*)%.[^.]+$")
if key then
tpl[str.gsub(key, "/", ".")] = readfile(path)
end
end
end
if not runtime then
for k, v in pairs(tpl) do
tpl[k] = mch(v, { partials = tpl })
end
return tpl
else
return mch([[
local mch = require("santoku.mustache")
local tpl = {{{embed}}}
for k, v in pairs(tpl) do
tpl[k] = mch(v, { partials = tpl })
end
return tpl
]])({ embed = serialize(tpl) })
end
end
Details
- The runtime branch instead renders a Lua module that embeds the serialized pack and recompiles the pack on load.