Overview of Bit Powder text templates, called hair
, and is like handlebars and mustache (and the earlier ctemplate original). In short the features and syntax:
Variables can be declared at top of an input file with
key: json-value
pairs. The first empty line signals the end of the the variables.Values with
{{=value}}
(supports expressions, see below);Conditionals with
{{if value}}then-part{{else}}else-part{{end}}
.Iterators with
{{for variable in value}}contents{{end}}
. Contents is displayed (if this default form is used) if value is an array. An iteration variable is specified withvariable
. To enumerate the values, use{{for (index,variable) in value}}contents{{end}}
.Template definition with
{{define name}}content{{end}}
. Templates can have optional default values (inobject
) with{{define name defaults object}}content{{end}}
. Defaults are resolved at template compile time, using the global context given to the compile function;Template instantation with
{{call name}}
or{{call name with value}}
.name
can be an expression. If the name starts with a*
,name
can be an expression that resolves to a string (which is treated as a template name). If the name starts with**
,name
should be an expression that resolves to a binary form template code (as produced by the compile functions).Error handling is different from normal Mustache: missing fields is always considered an error. Errors can be suppressed with the
expr ??? alternative
try syntax (on error inexpr
,alternative
will be executed). Shorthand forexpr ??? null
isexpr ???
, which can be used in loops with{{for i in someField???}}
ignoring errors if the field is not found. Same for conditionals.
binexpr
expressions can be used instead of values as above (think
of expressions, functional calls, selectors, etc). This utility supports
also Lua in the templates. Prefix anywhere a value is accepted with
lua:
to run Lua code (with current value in this
).
There are a couple of special functions added to the Binary Object expressions:
string compile(string template, [any context])
Compiles a string to a dynamic Mustache template that can be evaluated, and evaluates the defaults using the optional context context (otherwise empty context is used).string eval(string compiled_template, any context)
Evaluates a dynamic Mustache template using the context context.void set(string key, any value)
any get(string key)
Sets/retrieves a global value (useful for figure numbers etc).string filehash(string path)
string filewithhash(string path)
Calculates the xxhash32 for the contents of the file specified by path (relative to the--base
flag). Useful to support caching with a long TTL: setting the hash as query makes the URL unique for the content (if the content changes). The function call filewithhash(path) printspath?hash
.