Template
View as Markdownimport { Template } from '@memomori/obol'
new Template(name) is Go's template.New. Each method matches the Go method
of the same name, in camel case. Where Go returns an error, obol throws.
| Method | Does |
|---|---|
parse(text) |
Parses text as the body, and adds each {{define}} it holds |
execute(data?) |
Returns the rendered string |
executeTemplate(name, data) |
Renders the associated template name |
funcs({ name: fn }) |
Adds functions. Call it before parse, which rejects unknown names |
option('missingkey=error') |
Sets an option |
delims(left, right) |
Changes the delimiters from {{ and }} |
new(name) |
Makes a template that shares this one's definitions, functions and options |
lookup(name) |
Returns the associated template name, or undefined |
templates() |
Lists the associated templates |
definedTemplates() |
Names them, for an error message |
clone() |
Copies the whole set, so the copy can change without touching the original |
addParseTree(name, tree) |
Adds a tree from @memomori/obol/parse |
parse, funcs, option and delims return the template, so calls chain:
const page = new Template('page')
.option('missingkey=error')
.funcs({ upper: (text: string) => text.toUpperCase() })
.parse('{{.title | upper}}')
missingkey #
The option sets what a missing key in a plain object or Map does:
| Option | A missing key |
|---|---|
missingkey=default, missingkey=invalid |
prints <no value> |
missingkey=zero |
gives the zero value, which for any value also prints <no value> |
missingkey=error |
stops the run |
template: page:1:2: executing "page" at <.nope>: map has no entry for key "nope"
Use missingkey=error to catch a typo in a key. A class instance acts as a
struct, so a field it lacks fails under every option.
Delimiters #
new Template('page').delims('[[', ']]').parse('Hello, [[.name]]')
Set them before parse. Empty strings restore {{ and }}. Templates made
with new take the delimiters of the template they came from.
Concurrency #
A parsed template holds no state between runs, and execute runs to the end
before it returns. Share one parsed template across every request.