Docs menu

Parse trees

View as Markdown
import { parse } from '@memomori/obol/parse'
import { Template } from '@memomori/obol'

const trees = parse('page', 'Hello {{.name | printf "%q"}}', '', '', {
  printf: true,
})

const page = new Template('page')
for (const [name, tree] of trees) page.addParseTree(name, tree)

page.execute({ name: 'Ann' })

That returns Hello "Ann". parse(name, text, leftDelim, rightDelim, ...funcs) is Go's parse.Parse. It returns a Map from each template name to its Tree, one per define plus the body.

Pass every function name the text calls, builtins included: the parser checks names against these maps only. A value of true will do, since the parser reads only the keys. Empty strings keep the default delimiters.

Read a tree #

tree.root is a ListNode. Each node has a type, a pos in the text and a copy(). String(node) prints it back as template text:

for (const node of trees.get('page')!.root!.nodes) {
  console.log(node.type, String(node))
}
// text Hello
// action {{.name | printf "%q"}}

@memomori/obol/node exports each node class, from TextNode and ActionNode to IfNode, RangeNode and TemplateNode. Their fields match Go's text/template/parse.

isEmptyTree(node) tells whether a tree holds only white space and definitions. addParseTree uses it to keep an existing body.