Docs menu

Functions

View as Markdown

Call a function by name, with its arguments after it:

{{printf "%d items" (len .items)}}
{{.items | len | printf "%d items"}}

Logic #

Function Returns
and x y … the first false argument, or the last one
or x y … the first true argument, or the last one
not x whether x is false

and and or stop at the first argument that settles the answer, so {{and .user .user.admin}} never reads admin from a missing user.

Comparison #

Function True when
eq x y … x equals any of the others
ne x y x differs from y
lt x y x < y
le x y x <= y
gt x y x > y
ge x y x >= y

They compare booleans, numbers and strings, as Go does. Ordering needs two values of the same kind; {{lt 1 "a"}} is an error.

Values #

Function Returns
len x the length of a string, array, object, Map or Set
index x k … x[k], then the next key into that, and so on
slice x i j x from i up to j; slice x i runs to the end
call f args… the result of calling the function f
{{index .rows 0 "name"}}
{{slice .title 0 20}}
{{call .format .date}}

call runs a function you passed as data. A function stored on the data is a value, not a method, so {{.format .date}} fails; see Data.

Printing #

Function Returns
print x … its arguments, with a space between two that are not strings
println x … its arguments split by spaces, then a newline
printf format x … the format with each verb filled in

printf takes Go's verbs:

Verb Prints
%v, %+v, %#v the value in Go's default format
%T Go's name for the value's type
%s, %q a string, plain or quoted
%d, %b, %o, %O, %x, %X an integer in base 10, 2, 8 or 16
%c, %U a character, or its U+0041 form
%e, %E, %f, %F, %g, %G a number with a fraction or exponent
%t a boolean
%% a percent sign

Widths, precisions and the flags + - # 0 and space work as in Go: {{printf "%-8s|%6.2f" .name .price}}.

Escaping #

Function Escapes its arguments for
html x … HTML text and attribute values
js x … a JavaScript string
urlquery x … a URL query value

Each joins its arguments as print does, then escapes the result:

<a href="/search?q={{urlquery .query}}">{{html .query}}</a>

obol has no html/template, so nothing escapes on its own. Call these where the output needs them. @memomori/obol/funcs exports the same escapers as htmlEscape, jsEscape and urlQueryEscape.

Your own functions #

const page = new Template('page')
  .funcs({ upper: (text: string) => text.toUpperCase() })
  .parse('{{.name | upper}}')

Add functions before you parse: the parser rejects a name it does not know, with function "upper" not defined. A name must be a valid identifier.

Your function gets the arguments as JavaScript values and returns one value. If it throws, the run stops with error calling upper: …, and the ExecError holds what it threw as cause. obol never awaits a promise, so fetch what a template needs before you run it.

A function you add with the name of a builtin replaces it, as in Go.