Documentation
¶
Overview ¶
Package template implements text templates with expr expressions.
A template is text with actions. An action is written between "{{" and "}}". Execute copies the text to the output and runs the actions:
t := template.Must(template.New("hello").Parse("Hello, {{ name }}!\n"))
err := t.Execute(os.Stdout, map[string]any{"name": "Alice"})
A name in an expression is a key of the data, if the data is a map, or a field or a method, if the data is a struct. A field has the name in its expr struct tag, or its Go name if it has no tag. An expression can call the builtin functions of expr, such as len and upper.
The options of New are options of expr. expr.Function adds a function. expr.Env declares the type of the data, and Parse then type-checks the template and reports unknown names. Without expr.Env, a name that a map does not have is nil, and a name that a struct does not have is an error from Execute.
The package does not escape the output.
Actions ¶
Here is the list of actions.
{{ expression }}
The value of the expression is printed as fmt.Print prints
it, so nil is printed as <nil>. To override the printing
function, use Template.Print.
{{ /* a comment */ }}
A comment in the syntax of expr: /* text */, or // text up
to the end of the line. An action that contains only a
comment prints nothing. After a // comment, the closing "}}"
must be on the next line.
{{ if condition }} T1 {{ end }}
If the condition is true, T1 is executed. Otherwise no output
is generated. The condition is an expression, and its value
must be a boolean. Any other value, including nil, is an
error. To test whether a value is set, compare it with nil:
{{ if name != nil }}.
{{ if condition }} T1 {{ else }} T0 {{ end }}
If the condition is true, T1 is executed. Otherwise T0 is
executed.
{{ if condition }} T1 {{ else if condition }} T0 {{ end }}
The else action of an if can include another if directly.
The effect is the same as writing
{{ if condition }} T1 {{ else }}{{ if condition }} T0 {{ end }}{{ end }}
{{ for x in collection }} T1 {{ end }}
The collection is an expression, and its value must be a
slice, an array, or a map. Any other value, including nil, is
an error. T1 is executed for each element of the collection.
In T1, the variable x has the value of the element. If the
collection is empty, no output is generated.
{{ for i, x in collection }} T1 {{ end }}
This form has a second variable, i. For a slice or an array,
i has the index of the element, from 0. For a map, i has the
key of the element.
An action that starts with if, else, end, or for is always that kind of action. To start an expression with one of these words, put it in parentheses: "{{ (end) }}" prints the value of the name end, and "{{ (if a { 1 } else { 2 }) }}" is the if expression of expr.
Loops ¶
For a map, T1 is executed for the elements in sorted key order. The keys must all be strings, all be integers, or all be floats.
The variables of a for action exist only in T1. A variable shadows a name of the data, a function, or a variable of an enclosing for action with the same name. If Parse knows the type of the collection, it type-checks the uses of the variables.
Inside a for action, expressions read a copy of the data that is made when the loop starts. If a method called in the loop changes a field of the data, the expressions in the loop still read the old value. Without expr.Env, a name that the data does not have is nil inside a for action, even when it is an error outside one.
Text and spaces ¶
Trim markers remove the white space around an action. "{{- " removes all white space before the action, and " -}}" removes all white space after it:
"a {{- 1 -}} b" prints "a1b"
The minus sign must have white space between it and the expression. Otherwise it is part of the expression: "{{-3}}" prints "-3". White space is any character that expr treats as white space, such as a space, a tab, or a newline.
Example ¶
package main
import (
"log"
"os"
template "github.com/davidklassen/expr-template"
)
func main() {
t := template.Must(template.New("hello").Parse("Hello, {{ name }}!\n"))
err := t.Execute(os.Stdout, map[string]any{"name": "Alice"})
if err != nil {
log.Fatal(err)
}
}
Output: Hello, Alice!
Example (For) ¶
package main
import (
"log"
"os"
"github.com/expr-lang/expr"
template "github.com/davidklassen/expr-template"
)
func main() {
type Item struct {
Name string `expr:"name"`
Price float64 `expr:"price"`
}
type Env struct {
Items []Item `expr:"items"`
}
t := template.Must(template.New("order", expr.Env(Env{})).Parse(
"{{ for item in items }}{{ item.name }}: {{ item.price }}\n{{ end }}"))
err := t.Execute(os.Stdout, Env{Items: []Item{{"tea", 2.5}, {"cake", 4}}})
if err != nil {
log.Fatal(err)
}
}
Output: tea: 2.5 cake: 4
Example (ForMap) ¶
package main
import (
"log"
"os"
template "github.com/davidklassen/expr-template"
)
func main() {
t := template.Must(template.New("stock").Parse(
"{{ for name, count in stock }}{{ name }}: {{ count }}\n{{ end }}"))
err := t.Execute(os.Stdout, map[string]any{
"stock": map[string]int{"tea": 12, "cake": 3, "milk": 7},
})
if err != nil {
log.Fatal(err)
}
}
Output: cake: 3 milk: 7 tea: 12
Example (If) ¶
package main
import (
"log"
"os"
template "github.com/davidklassen/expr-template"
)
func main() {
t := template.Must(template.New("cart").Parse(
"{{ if n == 0 }}The cart is empty.{{ else if n == 1 }}1 item{{ else }}{{ n }} items{{ end }}\n"))
for _, n := range []int{0, 1, 5} {
err := t.Execute(os.Stdout, map[string]any{"n": n})
if err != nil {
log.Fatal(err)
}
}
}
Output: The cart is empty. 1 item 5 items
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ActionNode ¶ added in v0.2.0
type ActionNode struct {
Expr *Expr
// contains filtered or unexported fields
}
An ActionNode is an action that prints the value of an expression.
type Error ¶
type Error struct {
Name string // name of the template
Line int // line in the template, from 1
Column int // column in the line, in characters, from 1
Message string
// contains filtered or unexported fields
}
An Error records a problem in a template and its position.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/expr-lang/expr"
template "github.com/davidklassen/expr-template"
)
func main() {
type Env struct {
Name string `expr:"name"`
}
_, err := template.New("hello", expr.Env(Env{})).Parse("Hello, {{ nmae }}!\n")
fmt.Println(err)
if e, ok := errors.AsType[*template.Error](err); ok {
fmt.Println(e.Name, e.Line, e.Column)
}
}
Output: unknown name nmae (hello:1:11) | Hello, {{ nmae }}! | ..........^ hello 1 11
type Expr ¶ added in v0.2.0
An Expr is a compiled expression of a template. Its location covers the source of Program in the template text. To get the position of a node of the expr AST in the template, add Location().From to the location of the node.
type ForNode ¶ added in v0.2.0
type ForNode struct {
Key string // variable for the index or the map key, "" if not declared
Elem string // variable for the element
Collection *Expr
Body []Node
// contains filtered or unexported fields
}
A ForNode is a for action with its body. The location of a ForNode covers only the for action itself, from "{{" to "}}".
type IfNode ¶ added in v0.2.0
type IfNode struct {
Cond *Expr
Body []Node
ElseBody []Node
// contains filtered or unexported fields
}
An IfNode is an if action with its branches. An else if is an IfNode that is the only node of ElseBody. The location of an IfNode covers only the if action itself, from "{{" to "}}".
type Node ¶ added in v0.2.0
type Node interface {
// Location returns the position of the node in the template text. From
// and To are offsets in runes.
Location() file.Location
}
A Node is an element of the parse tree of a template. It is a *TextNode, an *ActionNode, an *IfNode, or a *ForNode.
type Template ¶
type Template struct {
// contains filtered or unexported fields
}
Template is a parsed template.
func Must ¶
Must is a helper that wraps a call to a function returning (*Template, error) and panics if the error is non-nil. It is intended for use in variable initializations such as
var t = template.Must(template.New("name").Parse("text"))
func New ¶
New returns a new template with the given name. The options apply to every expression of the template when Template.Parse compiles it.
Use expr.Env to declare the type of the data that Template.Execute receives. Parse then reports type errors and unknown names. Without expr.Env, Parse does not check the names.
Example ¶
package main
import (
"log"
"os"
"github.com/expr-lang/expr"
template "github.com/davidklassen/expr-template"
)
func main() {
type Env struct {
Items []string `expr:"items"`
Price float64 `expr:"price"`
}
// With expr.Env, Parse checks the names and types in the template.
t, err := template.New("order", expr.Env(Env{})).Parse(
"{{ len(items) }} items, total {{ price * len(items) }}\n")
if err != nil {
log.Fatal(err)
}
err = t.Execute(os.Stdout, Env{Items: []string{"a", "b"}, Price: 1.5})
if err != nil {
log.Fatal(err)
}
}
Output: 2 items, total 3
func (*Template) Execute ¶
Execute applies the template to data and writes the output to w. The expressions are evaluated with data as their env. Execute prints the value of each expression as fmt.Print does. To override the printing function, use Template.Print.
If an error occurs, Execute stops, but it can have written part of the output to w. An error in an action is an *Error with the position of the problem in the template. If a write to w fails, Execute returns that error unchanged.
A template may be executed safely in parallel. If parallel executions share a Writer, the output may be interleaved.
func (*Template) Nodes ¶ added in v0.2.0
Nodes returns the parse tree of the template: its top-level nodes in order. The tree must not be modified.
Example ¶
package main
import (
"fmt"
template "github.com/davidklassen/expr-template"
)
func main() {
t := template.Must(template.New("hello").Parse(
"Hello, {{ name }}!{{ if admin }} You are an admin.{{ end }}\n"))
for _, n := range t.Nodes() {
switch n := n.(type) {
case *template.TextNode:
fmt.Printf("text %q\n", n.Text)
case *template.ActionNode:
fmt.Printf("action %q\n", n.Expr.Program.Source())
case *template.IfNode:
fmt.Printf("if %q with %d nodes\n", n.Cond.Program.Source(), len(n.Body))
}
}
}
Output: text "Hello, " action "name" text "!" if "admin" with 1 nodes text "\n"
func (*Template) Parse ¶
Parse parses text as the body of the template and compiles its expressions.
If an error occurs, Parse returns nil and the error. The error is an *Error with the position of the problem in text.
func (*Template) Print ¶ added in v0.2.0
Print overrides the function that converts the value of an action to text. The default is fmt.Sprint. If f returns an error, Execute stops and returns an *Error that wraps it. If the template is executed in parallel, f must be safe for concurrent use.
Example ¶
package main
import (
"errors"
"fmt"
"io"
template "github.com/davidklassen/expr-template"
)
func main() {
print := func(v any) (string, error) {
if v == nil {
return "", errors.New("no value")
}
return fmt.Sprint(v), nil
}
// The template has a typo: passwrd.
t := template.Must(template.New("config").Print(print).Parse(
"user = {{ db.user }}\npassword = {{ db.passwrd }}\n"))
err := t.Execute(io.Discard, map[string]any{
"db": map[string]any{"user": "app", "password": "secret"},
})
fmt.Println(err)
}
Output: no value (config:2:12) | password = {{ db.passwrd }} | ...........^