template

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

expr-template

Go text templates with expr expressions.

go get github.com/davidklassen/expr-template

The package documentation describes the template syntax.

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.

func (*ActionNode) Location added in v0.2.0

func (n *ActionNode) Location() file.Location

Location returns the position in the template text. From and To are offsets in runes.

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

func (*Error) Error

func (e *Error) Error() string

Error returns the message, the position, and the snippet.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the cause of e, or nil if it has none. If a function that the template calls returns an error, that error is the cause. An error from the printing function is the cause too.

type Expr added in v0.2.0

type Expr struct {
	Program *vm.Program
	// contains filtered or unexported fields
}

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.

func (*Expr) Location added in v0.2.0

func (n *Expr) Location() file.Location

Location returns the position in the template text. From and To are offsets in runes.

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 "}}".

func (*ForNode) Location added in v0.2.0

func (n *ForNode) Location() file.Location

Location returns the position in the template text. From and To are offsets in runes.

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 "}}".

func (*IfNode) Location added in v0.2.0

func (n *IfNode) Location() file.Location

Location returns the position in the template text. From and To are offsets in runes.

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

func Must(t *Template, err error) *Template

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

func New(name string, opts ...expr.Option) *Template

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

func (t *Template) Execute(w io.Writer, data any) error

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) Name

func (t *Template) Name() string

Name returns the name of the template.

func (*Template) Nodes added in v0.2.0

func (t *Template) Nodes() []Node

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

func (t *Template) Parse(text string) (*Template, error)

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

func (t *Template) Print(f func(v any) (string, error)) *Template

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 }}
 | ...........^

type TextNode added in v0.2.0

type TextNode struct {
	Text string
	// contains filtered or unexported fields
}

A TextNode is text between actions.

func (*TextNode) Location added in v0.2.0

func (n *TextNode) Location() file.Location

Location returns the position in the template text. From and To are offsets in runes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL