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>.
{{ /* 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 list }} T1 {{ end }}
The list 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 list. In T1, the
variable x has the value of the element. If the list is
empty, no output is generated.
{{ for i, x in list }} 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 list, 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 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 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.
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.