template

package module
v1.14.2 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2020 License: BSD-3-Clause Imports: 17 Imported by: 0

README

Go template extended

Overview

This package is intended to extend the default go package text/template. Since it is not possible to access the internals of the original package, the whole source code has been duplicated and is regularly updated to implement the latest changes in the original go distribution.

Most changes have been done in distinct files to avoid merging conflict with the original library.

By default, there is no difference between this library and the original one except the following exception:

If you register a function that only return error:

t := template.New("test").Funcs(template.FuncMap{
    "my_func": func() error { return fmt.Errorf("bang") },
})

That will raise the following error: can't install method/function "my_func" with only error as result.

To avoid this error, you will have to register your functions with ExtraFuncs method instead of Funcs.

Usage

Instead of importing like this:

package your_package

import (
    "text/template"
)

// Your code
// ...

You import it list this:

package your_package

import (
    "github.com/jocgir/template"
)

// Your code
// ...

What's different in this implementation

Handling non standard return functions

The original library will fail if you try to register custom functions that have no returns or returns multiple values.

t := template.New("test").Funcs(template.FuncMap{
    // Will raise: can't install method/function "empty" with 0 results
    "empty": func() { ... },
})
t := template.New("test").Funcs(template.FuncMap{
    // Will raise: can't install method/function "multiple" with 2 results
    "multiple": func() (int, string) { return 0, "Zero" }, results
})

But using this ExtraFuncs to register functions will handle these exceptions:

t := template.New("test").ExtraFuncs(template.FuncMap{
    "empty":    func() { ... },
    "multiple": func() (int, string) { return 0, "Zero" },results
})

One problem with the original library is that non-compliant custom functions are detected at registration, but calling non-compliant methods fail at runtime as you can see in that example.

Custom error handling functions

When an error occurs while executing a template, there is no way to recuperate on that error. However, it could be useful to have a mechanism to dynamically fix the error and continue the processing.

So we added the ErrorManagers method to template. With this method, it is possible to provide custom error management functions and also specify filters to determine when this function should be invoked.

    errorHandlerFunc := func(context *template.Context) (interface{}, ErrorAction) {
        return fmt.Sprintf("ErrorHandled %v", context.Error()), template.ResultReplaced
    }

    handler := template.NewErrorManager(errorHandlerFunc).OnSources(template.Call)
    t := template.New("managed").ErrorManagers("name", template.NewErrorManager())

Documentation

Overview

Package template implements data-driven templates for generating textual output.

To generate HTML output, see package html/template, which has the same interface as this package but automatically secures HTML output against certain attacks.

Templates are executed by applying them to a data structure. Annotations in the template refer to elements of the data structure (typically a field of a struct or a key in a map) to control execution and derive values to be displayed. Execution of the template walks the structure and sets the cursor, represented by a period '.' and called "dot", to the value at the current location in the structure as execution proceeds.

The input text for a template is UTF-8-encoded text in any format. "Actions"--data evaluations or control structures--are delimited by "{{" and "}}"; all text outside actions is copied to the output unchanged. Except for raw strings, actions may not span newlines, although comments can.

Once parsed, a template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

Here is a trivial example that prints "17 items are made of wool".

type Inventory struct {
	Material string
	Count    uint
}
sweaters := Inventory{"wool", 17}
tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
if err != nil { panic(err) }
err = tmpl.Execute(os.Stdout, sweaters)
if err != nil { panic(err) }

More intricate examples appear below.

Text and spaces

By default, all text between actions is copied verbatim when the template is executed. For example, the string " items are made of " in the example above appears on standard output when the program is run.

However, to aid in formatting template source code, if an action's left delimiter (by default "{{") is followed immediately by a minus sign and ASCII space character ("{{- "), all trailing white space is trimmed from the immediately preceding text. Similarly, if the right delimiter ("}}") is preceded by a space and minus sign (" -}}"), all leading white space is trimmed from the immediately following text. In these trim markers, the ASCII space must be present; "{{-3}}" parses as an action containing the number -3.

For instance, when executing the template whose source is

"{{23 -}} < {{- 45}}"

the generated output would be

"23<45"

For this trimming, the definition of white space characters is the same as in Go: space, horizontal tab, carriage return, and newline.

Actions

Here is the list of actions. "Arguments" and "pipelines" are evaluations of data, defined in detail in the corresponding sections that follow.

{{/* a comment */}}
{{- /* a comment with white space trimmed from preceding and following text */ -}}
	A comment; discarded. May contain newlines.
	Comments do not nest and must start and end at the
	delimiters, as shown here.

{{pipeline}}
	The default textual representation (the same as would be
	printed by fmt.Print) of the value of the pipeline is copied
	to the output.

{{if pipeline}} T1 {{end}}
	If the value of the pipeline is empty, no output is generated;
	otherwise, T1 is executed. The empty values are false, 0, any
	nil pointer or interface value, and any array, slice, map, or
	string of length zero.
	Dot is unaffected.

{{if pipeline}} T1 {{else}} T0 {{end}}
	If the value of the pipeline is empty, T0 is executed;
	otherwise, T1 is executed. Dot is unaffected.

{{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
	To simplify the appearance of if-else chains, the else action
	of an if may include another if directly; the effect is exactly
	the same as writing
		{{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}}

{{range pipeline}} T1 {{end}}
	The value of the pipeline must be an array, slice, map, or channel.
	If the value of the pipeline has length zero, nothing is output;
	otherwise, dot is set to the successive elements of the array,
	slice, or map and T1 is executed. If the value is a map and the
	keys are of basic type with a defined order, the elements will be
	visited in sorted key order.

{{range pipeline}} T1 {{else}} T0 {{end}}
	The value of the pipeline must be an array, slice, map, or channel.
	If the value of the pipeline has length zero, dot is unaffected and
	T0 is executed; otherwise, dot is set to the successive elements
	of the array, slice, or map and T1 is executed.

{{template "name"}}
	The template with the specified name is executed with nil data.

{{template "name" pipeline}}
	The template with the specified name is executed with dot set
	to the value of the pipeline.

{{block "name" pipeline}} T1 {{end}}
	A block is shorthand for defining a template
		{{define "name"}} T1 {{end}}
	and then executing it in place
		{{template "name" pipeline}}
	The typical use is to define a set of root templates that are
	then customized by redefining the block templates within.

{{with pipeline}} T1 {{end}}
	If the value of the pipeline is empty, no output is generated;
	otherwise, dot is set to the value of the pipeline and T1 is
	executed.

{{with pipeline}} T1 {{else}} T0 {{end}}
	If the value of the pipeline is empty, dot is unaffected and T0
	is executed; otherwise, dot is set to the value of the pipeline
	and T1 is executed.

Arguments

An argument is a simple value, denoted by one of the following.

  • A boolean, string, character, integer, floating-point, imaginary or complex constant in Go syntax. These behave like Go's untyped constants. Note that, as in Go, whether a large integer constant overflows when assigned or passed to a function can depend on whether the host machine's ints are 32 or 64 bits.
  • The keyword nil, representing an untyped Go nil.
  • The character '.' (period): . The result is the value of dot.
  • A variable name, which is a (possibly empty) alphanumeric string preceded by a dollar sign, such as $piOver2 or $ The result is the value of the variable. Variables are described below.
  • The name of a field of the data, which must be a struct, preceded by a period, such as .Field The result is the value of the field. Field invocations may be chained: .Field1.Field2 Fields can also be evaluated on variables, including chaining: $x.Field1.Field2
  • The name of a key of the data, which must be a map, preceded by a period, such as .Key The result is the map element value indexed by the key. Key invocations may be chained and combined with fields to any depth: .Field1.Key1.Field2.Key2 Although the key must be an alphanumeric identifier, unlike with field names they do not need to start with an upper case letter. Keys can also be evaluated on variables, including chaining: $x.key1.key2
  • The name of a niladic method of the data, preceded by a period, such as .Method The result is the value of invoking the method with dot as the receiver, dot.Method(). Such a method must have one return value (of any type) or two return values, the second of which is an error. If it has two and the returned error is non-nil, execution terminates and an error is returned to the caller as the value of Execute. Method invocations may be chained and combined with fields and keys to any depth: .Field1.Key1.Method1.Field2.Key2.Method2 Methods can also be evaluated on variables, including chaining: $x.Method1.Field
  • The name of a niladic function, such as fun The result is the value of invoking the function, fun(). The return types and values behave as in methods. Functions and function names are described below.
  • A parenthesized instance of one the above, for grouping. The result may be accessed by a field or map key invocation. print (.F1 arg1) (.F2 arg2) (.StructValuedMethod "arg").Field

Arguments may evaluate to any type; if they are pointers the implementation automatically indirects to the base type when required. If an evaluation yields a function value, such as a function-valued field of a struct, the function is not invoked automatically, but it can be used as a truth value for an if action and the like. To invoke it, use the call function, defined below.

Pipelines

A pipeline is a possibly chained sequence of "commands". A command is a simple value (argument) or a function or method call, possibly with multiple arguments:

Argument
	The result is the value of evaluating the argument.
.Method [Argument...]
	The method can be alone or the last element of a chain but,
	unlike methods in the middle of a chain, it can take arguments.
	The result is the value of calling the method with the
	arguments:
		dot.Method(Argument1, etc.)
functionName [Argument...]
	The result is the value of calling the function associated
	with the name:
		function(Argument1, etc.)
	Functions and function names are described below.

A pipeline may be "chained" by separating a sequence of commands with pipeline characters '|'. In a chained pipeline, the result of each command is passed as the last argument of the following command. The output of the final command in the pipeline is the value of the pipeline.

The output of a command will be either one value or two values, the second of which has type error. If that second value is present and evaluates to non-nil, execution terminates and the error is returned to the caller of Execute.

Variables

A pipeline inside an action may initialize a variable to capture the result. The initialization has syntax

$variable := pipeline

where $variable is the name of the variable. An action that declares a variable produces no output.

Variables previously declared can also be assigned, using the syntax

$variable = pipeline

If a "range" action initializes a variable, the variable is set to the successive elements of the iteration. Also, a "range" may declare two variables, separated by a comma:

range $index, $element := pipeline

in which case $index and $element are set to the successive values of the array/slice index or map key and element, respectively. Note that if there is only one variable, it is assigned the element; this is opposite to the convention in Go range clauses.

A variable's scope extends to the "end" action of the control structure ("if", "with", or "range") in which it is declared, or to the end of the template if there is no such control structure. A template invocation does not inherit variables from the point of its invocation.

When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.

Examples

Here are some example one-line templates demonstrating pipelines and variables. All produce the quoted word "output":

{{"\"output\""}}
	A string constant.
{{`"output"`}}
	A raw string constant.
{{printf "%q" "output"}}
	A function call.
{{"output" | printf "%q"}}
	A function call whose final argument comes from the previous
	command.
{{printf "%q" (print "out" "put")}}
	A parenthesized argument.
{{"put" | printf "%s%s" "out" | printf "%q"}}
	A more elaborate call.
{{"output" | printf "%s" | printf "%q"}}
	A longer chain.
{{with "output"}}{{printf "%q" .}}{{end}}
	A with action using dot.
{{with $x := "output" | printf "%q"}}{{$x}}{{end}}
	A with action that creates and uses a variable.
{{with $x := "output"}}{{printf "%q" $x}}{{end}}
	A with action that uses the variable in another action.
{{with $x := "output"}}{{$x | printf "%q"}}{{end}}
	The same, but pipelined.

Functions

During execution functions are found in two function maps: first in the template, then in the global function map. By default, no functions are defined in the template but the Funcs method can be used to add them.

Predefined global functions are named as follows.

and
	Returns the boolean AND of its arguments by returning the
	first empty argument or the last argument, that is,
	"and x y" behaves as "if x then y else x". All the
	arguments are evaluated.
call
	Returns the result of calling the first argument, which
	must be a function, with the remaining arguments as parameters.
	Thus "call .X.Y 1 2" is, in Go notation, dot.X.Y(1, 2) where
	Y is a func-valued field, map entry, or the like.
	The first argument must be the result of an evaluation
	that yields a value of function type (as distinct from
	a predefined function such as print). The function must
	return either one or two result values, the second of which
	is of type error. If the arguments don't match the function
	or the returned error value is non-nil, execution stops.
html
	Returns the escaped HTML equivalent of the textual
	representation of its arguments. This function is unavailable
	in html/template, with a few exceptions.
index
	Returns the result of indexing its first argument by the
	following arguments. Thus "index x 1 2 3" is, in Go syntax,
	x[1][2][3]. Each indexed item must be a map, slice, or array.
slice
	slice returns the result of slicing its first argument by the
	remaining arguments. Thus "slice x 1 2" is, in Go syntax, x[1:2],
	while "slice x" is x[:], "slice x 1" is x[1:], and "slice x 1 2 3"
	is x[1:2:3]. The first argument must be a string, slice, or array.
js
	Returns the escaped JavaScript equivalent of the textual
	representation of its arguments.
len
	Returns the integer length of its argument.
not
	Returns the boolean negation of its single argument.
or
	Returns the boolean OR of its arguments by returning the
	first non-empty argument or the last argument, that is,
	"or x y" behaves as "if x then x else y". All the
	arguments are evaluated.
print
	An alias for fmt.Sprint
printf
	An alias for fmt.Sprintf
println
	An alias for fmt.Sprintln
urlquery
	Returns the escaped value of the textual representation of
	its arguments in a form suitable for embedding in a URL query.
	This function is unavailable in html/template, with a few
	exceptions.

The boolean functions take any zero value to be false and a non-zero value to be true.

There is also a set of binary comparison operators defined as functions:

eq
	Returns the boolean truth of arg1 == arg2
ne
	Returns the boolean truth of arg1 != arg2
lt
	Returns the boolean truth of arg1 < arg2
le
	Returns the boolean truth of arg1 <= arg2
gt
	Returns the boolean truth of arg1 > arg2
ge
	Returns the boolean truth of arg1 >= arg2

For simpler multi-way equality tests, eq (only) accepts two or more arguments and compares the second and subsequent to the first, returning in effect

arg1==arg2 || arg1==arg3 || arg1==arg4 ...

(Unlike with || in Go, however, eq is a function call and all the arguments will be evaluated.)

The comparison functions work on any values whose type Go defines as comparable. For basic types such as integers, the rules are relaxed: size and exact type are ignored, so any integer value, signed or unsigned, may be compared with any other integer value. (The arithmetic value is compared, not the bit pattern, so all negative integers are less than all unsigned integers.) However, as usual, one may not compare an int with a float32 and so on.

Associated templates

Each template is named by a string specified when it is created. Also, each template is associated with zero or more other templates that it may invoke by name; such associations are transitive and form a name space of templates.

A template may use a template invocation to instantiate another associated template; see the explanation of the "template" action above. The name must be that of a template associated with the template that contains the invocation.

Nested template definitions

When parsing a template, another template may be defined and associated with the template being parsed. Template definitions must appear at the top level of the template, much like global variables in a Go program.

The syntax of such definitions is to surround each template declaration with a "define" and "end" action.

The define action names the template being created by providing a string constant. Here is a simple example:

`{{define "T1"}}ONE{{end}}
{{define "T2"}}TWO{{end}}
{{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}}
{{template "T3"}}`

This defines two templates, T1 and T2, and a third T3 that invokes the other two when it is executed. Finally it invokes T3. If executed this template will produce the text

ONE TWO

By construction, a template may reside in only one association. If it's necessary to have a template addressable from multiple associations, the template definition must be parsed multiple times to create distinct *Template values, or must be copied with the Clone or AddParseTree method.

Parse may be called multiple times to assemble the various associated templates; see the ParseFiles and ParseGlob functions and methods for simple ways to parse related templates stored in files.

A template may be executed directly or through ExecuteTemplate, which executes an associated template identified by name. To invoke our example above, we might write,

err := tmpl.Execute(os.Stdout, "no data needed")
if err != nil {
	log.Fatalf("execution failed: %s", err)
}

or to invoke a particular template explicitly by name,

err := tmpl.ExecuteTemplate(os.Stdout, "T2", "no data needed")
if err != nil {
	log.Fatalf("execution failed: %s", err)
}

Index

Examples

Constants

View Source
const (
	// FuncsAsMethodsID is the ID used to register the FunctionsAsMethods handler.
	FuncsAsMethodsID = "^0_FuncsAsMethods"
	// ContextID is the ID used to register the FunctionsWithContext handler.
	ContextID = "^1_ContextHandlers"
	// CallFailID is the ID used to register the trap handler.
	CallFailID = "^2_CallFailHandler"
)
View Source
const NoValue = "<no value>"

NoValue is the rendered string representation of invalid value if missingkey is set to invalid or left to default.

Variables

This section is empty.

Functions

func HTMLEscape

func HTMLEscape(w io.Writer, b []byte)

HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.

func HTMLEscapeString

func HTMLEscapeString(s string) string

HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.

func HTMLEscaper

func HTMLEscaper(args ...interface{}) string

HTMLEscaper returns the escaped HTML equivalent of the textual representation of its arguments.

func IsTrue

func IsTrue(val interface{}) (truth, ok bool)

IsTrue reports whether the value is 'true', in the sense of not the zero of its type, and whether the value has a meaningful truth value. This is the definition of truth used by if and other such actions.

func JSEscape

func JSEscape(w io.Writer, b []byte)

JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.

func JSEscapeString

func JSEscapeString(s string) string

JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.

func JSEscaper

func JSEscaper(args ...interface{}) string

JSEscaper returns the escaped JavaScript equivalent of the textual representation of its arguments.

func URLQueryEscaper

func URLQueryEscaper(args ...interface{}) string

URLQueryEscaper returns the escaped value of the textual representation of its arguments in a form suitable for embedding in a URL query.

Types

type Context added in v1.14.1

type Context struct {
	// contains filtered or unexported fields
}

Context gives the current context error information to the error handler.

func (*Context) ArgCount added in v1.14.2

func (c *Context) ArgCount() int

ArgCount return the total number of argument supplied to the context including the piped argument if there is.

func (*Context) Call added in v1.14.2

func (c *Context) Call(function interface{}) interface{}

Call invokes the supplied function with the arguments supplied in the context. If function is nil, the function attached to the context will be called. The function an be either a reflect.Value, a function prototype or the name of a registered function.

func (*Context) ClearError added in v1.14.2

func (c *Context) ClearError()

ClearError is used by error managers to indicate that an error condition has been solved.

func (*Context) Current added in v1.14.2

func (c *Context) Current() reflect.Value

Current returns the current context designated by dot {{ . }}.

func (*Context) Error added in v1.14.2

func (c *Context) Error() error

Error returns the current error condition associated with the context.

func (*Context) Errorf added in v1.14.2

func (c *Context) Errorf(format string, args ...interface{})

Errorf allows handlers to set the current error state by formatting the error message.

func (*Context) EvalArgs added in v1.14.2

func (c *Context) EvalArgs() []interface{}

EvalArgs returns an []interface{} from the supplied arguments. If there is a piped argument, it will be added at the end. If there is a receiver, it will be inserted as the first argument.

func (*Context) Global added in v1.14.2

func (c *Context) Global() reflect.Value

Global returns the global context designated by string {{ $ }}.

func (*Context) Match added in v1.14.2

func (c *Context) Match(name interface{}) string

Match returns the designated group in error matching regex. It is under the user responsability to supply a valid regular expression to match the error text. Within that expression, user can defines anonymous subexpression group using (.*) or named subexpression (?P<name>.*). Context.Match(0) will return the whole match. Context.Match(n) will return the nth submatch group. Context.Match("name") will return the named submatch group.

func (*Context) MemberName added in v1.14.2

func (c *Context) MemberName() string

MemberName returns the faulting member that created the context, either field name or method name.

func (*Context) Node added in v1.14.2

func (c *Context) Node() parse.Node

Node returns the current node that's being processed by go template.

func (*Context) PipelineArg added in v1.14.2

func (c *Context) PipelineArg() reflect.Value

PipelineArg returns the argument supplied through pipeline.

func (*Context) Receiver added in v1.14.2

func (c *Context) Receiver() reflect.Value

Receiver returns the current object receiver (i.e. the object on witch a field or a method is called upon).

func (*Context) Recover added in v1.14.2

func (c *Context) Recover()

Recover allows user writing function dealing with context to ensure that any unmanaged error will be handled properly. Simply add the following call at the begining of your function:

func(context *Context) result {
  defer context.Recover()
  ...
}

func (*Context) Result added in v1.14.2

func (c *Context) Result() *reflect.Value

Result returns the current result value that will be returned by the context.

func (*Context) SetError added in v1.14.2

func (c *Context) SetError(err error)

SetError allows handlers to set the current error state.

func (*Context) StackLen added in v1.14.2

func (c *Context) StackLen() int

StackLen returns the current stack length.

func (*Context) StackPeek added in v1.14.2

func (c *Context) StackPeek(n int) *StackCall

StackPeek returns the nth value in the template calling stack (0 meaning the current function).

func (*Context) Template added in v1.14.2

func (c *Context) Template() *Template

Template returns the current template being evaluated.

func (*Context) Trapped added in v1.14.2

func (c *Context) Trapped() bool

Trapped returns true if the current call errors are being catched by trap function.

func (*Context) TryCall added in v1.14.2

func (c *Context) TryCall(function interface{}) (interface{}, bool)

TryCall tries to invokes the supplied function with the arguments supplied in the context. If it is not possible to invoke the function, a false value will be returned as second return value. If the function exist, the second value will be true even if the call fails. Check Error() method to get the result of the call.

func (*Context) Variables added in v1.14.2

func (c *Context) Variables() Map

Variables returns the current variable values available through {{ $variable }}.

type ContextSource added in v1.14.1

type ContextSource byte

ContextSource defines the type of error that could be managed by the error handlers.

const (
	// FieldError indicates that the context has been created while evaluating field.
	FieldError ContextSource = 1 << iota
	// CallContext indicates that the context has been created while evaluating function call requiring *Context argument.
	CallContext
	// CallError indicates that the context has been created on error while evaluating function call.
	CallError
	// Print indicates that the context has been created while evaluating object without String() method.
	Print
	// Call indicates that the context has been created while evaluating function call (context or error).
	Call = CallContext | CallError
)

func (ContextSource) IsSet added in v1.14.1

func (s ContextSource) IsSet(value ContextSource) bool

IsSet check whether or not the source has the specified value set.

func (ContextSource) String added in v1.14.1

func (s ContextSource) String() string

type ErrorAction

type ErrorAction uint8

ErrorAction defines the action done by external handler when managing missing key.

const (
	// NoReplace is returned if the external handler has not been able to fix the missing key.
	NoReplace ErrorAction = iota
	// ResultReplaced is returned if the external handler returned a valid replacement for the missing key.
	ResultReplaced
	// ResultAsArray is returned if the external handler returned an array on which we should apply the missing key.
	ResultAsArray
)

func (ErrorAction) String

func (a ErrorAction) String() string

type ErrorHandler

type ErrorHandler func(context *Context) (interface{}, ErrorAction)

ErrorHandler represents the function type used to try to recover missing key during the template evaluation.

type ErrorManager

type ErrorManager struct {
	// contains filtered or unexported fields
}

ErrorManager represents a pre-packaged ErrorHandler function.

func NewErrorManager added in v1.14.1

func NewErrorManager(handler ErrorHandler, filters ...string) *ErrorManager

NewErrorManager creates an ErrorManager object.

func (*ErrorManager) CanManage

func (em *ErrorManager) CanManage(context *Context) bool

CanManage returns true if the error manager can handle the kind of error.

func (*ErrorManager) Filters added in v1.14.1

func (em *ErrorManager) Filters(filters ...string) *ErrorManager

Filters indicates what errors pattern are processed by this manager. filters must be valid regular expressions. If the filter contains subexpression such as (?P<name>.*), the name will be available through context.Match("name"). If is also possible to access the match by calling context(n) where:

0 the whole match
1 the first matching group and so on

func (*ErrorManager) OnActions added in v1.14.1

func (em *ErrorManager) OnActions(modes ...MissingAction) *ErrorManager

OnActions indicates the error action mode handled by this manager.

func (*ErrorManager) OnKinds added in v1.14.1

func (em *ErrorManager) OnKinds(kinds ...reflect.Kind) *ErrorManager

OnKinds indicates the faulty receiver kind handled by this manager.

func (*ErrorManager) OnMembers added in v1.14.1

func (em *ErrorManager) OnMembers(members ...string) *ErrorManager

OnMembers indicates the faulty members handled by this manager.

func (*ErrorManager) OnSources added in v1.14.1

func (em *ErrorManager) OnSources(sources ...ContextSource) *ErrorManager

OnSources indicates the error source handled by this manager.

type ErrorManagers added in v1.14.1

type ErrorManagers []*ErrorManager

ErrorManagers represents a list of ErrorManager.

type ExecError

type ExecError struct {
	Name string // Name of template.
	Err  error  // Pre-formatted error.
}

ExecError is the custom error type returned when Execute has an error evaluating its template. (If a write error occurs, the actual error is returned; it will not be of type ExecError.)

func (ExecError) Error

func (e ExecError) Error() string

func (ExecError) Unwrap

func (e ExecError) Unwrap() error

type FuncMap

type FuncMap map[string]interface{}

FuncMap is the type of the map defining the mapping from names to functions. Each function must have either a single return value, or two return values of which the second has type error. In that case, if the second (error) return value evaluates to non-nil during execution, execution terminates and Execute returns that error.

When template execution invokes a function with an argument list, that list must be assignable to the function's parameter types. Functions meant to apply to arguments of arbitrary type can use parameters of type interface{} or of type reflect.Value. Similarly, functions meant to return a result of arbitrary type can return interface{} or reflect.Value.

type Map added in v1.14.1

type Map map[string]interface{}

Map represent a generic map with strings as keys.

type MissingAction

type MissingAction uint8

MissingAction is the public representation of the private missingKeyAction

const (
	// Default is used to return invalid reflect.Value when undefined.
	Default MissingAction = 1 << iota
	// ZeroValue indicates to return the zero value for the map element when undefined.
	ZeroValue
	// Error indicates that missing elements should be considered as error.
	Error
	// Invalid defaults to Default
	Invalid = Default
)

func (MissingAction) IsSet added in v1.14.1

func (a MissingAction) IsSet(value MissingAction) bool

IsSet check whether or not the action has the specified value set.

func (MissingAction) String

func (a MissingAction) String() string

type Option added in v1.14.2

type Option int

Option is used to enable additional options on template.

const (
	// FunctionsAsMethods let regular functions to be called as if they are methods of the first argument supplied.
	//
	// It is the indented to act as the opposite of the pipeline mechanism which consider the pipeline argument as
	// the last parameter while Jinja template (Python) consider the piped argument as the first one.
	//
	// Ex:
	//   {{ index $map $key }}   Regular call
	//   {{ $key | index $map }} Piped version
	//   {{ $map.index $key }}   Method version
	FunctionsAsMethods Option = 1 << iota

	// FunctionsWithContext allows user to provide custom function that support custom handling of parameters.
	//
	// The provided function must have the following signature:
	//   func UserFunction(context *template.Context) result
	// The result can be of any type.
	//
	// Then, if the user can call the registered function with any parameters without causing an error. The
	// parameters will have to be interpreted by the user function.
	//
	// Note that this option is automatically enabled if you register a non standard function using the ExtraFuncs
	// method instead of the standard Funcs method.
	FunctionsWithContext

	// Trap adds the function 'trap' that allows user to catch the return of a failing function call and
	// and continue the template evaluation.
	//
	// {{ if not trap custom_func }}
	// {{ end }}
	Trap

	// Eval option add the function 'eval' to the template available functions. Using that function,
	// a user is able to dynamically add build additional templates during the template execution and
	// execute them.
	//
	// {{ value := "test" }}
	// {{ eval "Hello {{ $value }}" }}
	Eval

	// FlowControl option enables functions to control the execution flow within the template:
	//   {{ break }}    is used within range block to quit the loop
	//   {{ continue }} is used within range block to skip the rest of the block and go to next element
	//   {{ return }}   is used to quit the current template
	FlowControl

	// NonStandardResults enables functions and methods to have no return or more than one returned values.
	// Note that this is simply an alias to FunctionsWithContext and that it is automatically enabled when
	// registering non standard functions with ExtraFuncs method. However, it is required to activate that
	// option for non standard methods returns.
	NonStandardResults = FunctionsWithContext

	// AllOptions enables all available options.
	AllOptions = ^Option(0)
)

type StackCall added in v1.14.1

type StackCall struct {
	Name     string
	Function reflect.Type
}

StackCall returns information about a stack element.

type Template

type Template struct {
	*parse.Tree
	// contains filtered or unexported fields
}

Template is the representation of a parsed template. The *parse.Tree field is exported only for use by html/template and should be treated as unexported by all other clients.

Example
package main

import (
	"log"
	"os"

	"github.com/jocgir/template"
)

func main() {
	// Define a template.
	const letter = `
Dear {{.Name}},
{{if .Attended}}
It was a pleasure to see you at the wedding.
{{- else}}
It is a shame you couldn't make it to the wedding.
{{- end}}
{{with .Gift -}}
Thank you for the lovely {{.}}.
{{end}}
Best wishes,
Josie
`

	// Prepare some data to insert into the template.
	type Recipient struct {
		Name, Gift string
		Attended   bool
	}
	var recipients = []Recipient{
		{"Aunt Mildred", "bone china tea set", true},
		{"Uncle John", "moleskin pants", false},
		{"Cousin Rodney", "", false},
	}

	// Create a new template and parse the letter into it.
	t := template.Must(template.New("letter").Parse(letter))

	// Execute the template for each recipient.
	for _, r := range recipients {
		err := t.Execute(os.Stdout, r)
		if err != nil {
			log.Println("executing template:", err)
		}
	}

}
Output:
Dear Aunt Mildred,

It was a pleasure to see you at the wedding.
Thank you for the lovely bone china tea set.

Best wishes,
Josie

Dear Uncle John,

It is a shame you couldn't make it to the wedding.
Thank you for the lovely moleskin pants.

Best wishes,
Josie

Dear Cousin Rodney,

It is a shame you couldn't make it to the wedding.

Best wishes,
Josie
Example (Block)
package main

import (
	"log"
	"os"
	"strings"

	"github.com/jocgir/template"
)

func main() {
	const (
		master  = `Names:{{block "list" .}}{{"\n"}}{{range .}}{{println "-" .}}{{end}}{{end}}`
		overlay = `{{define "list"}} {{join . ", "}}{{end}} `
	)
	var (
		funcs     = template.FuncMap{"join": strings.Join}
		guardians = []string{"Gamora", "Groot", "Nebula", "Rocket", "Star-Lord"}
	)
	masterTmpl, err := template.New("master").Funcs(funcs).Parse(master)
	if err != nil {
		log.Fatal(err)
	}
	overlayTmpl, err := template.Must(masterTmpl.Clone()).Parse(overlay)
	if err != nil {
		log.Fatal(err)
	}
	if err := masterTmpl.Execute(os.Stdout, guardians); err != nil {
		log.Fatal(err)
	}
	if err := overlayTmpl.Execute(os.Stdout, guardians); err != nil {
		log.Fatal(err)
	}
}
Output:
Names:
- Gamora
- Groot
- Nebula
- Rocket
- Star-Lord
Names: Gamora, Groot, Nebula, Rocket, Star-Lord
Example (Func)

This example demonstrates a custom function to process template text. It installs the strings.Title function and uses it to Make Title Text Look Good In Our Template's Output.

package main

import (
	"log"
	"os"
	"strings"

	"github.com/jocgir/template"
)

func main() {
	// First we create a FuncMap with which to register the function.
	funcMap := template.FuncMap{
		// The name "title" is what the function will be called in the template text.
		"title": strings.Title,
	}

	// A simple template definition to test our function.
	// We print the input text several ways:
	// - the original
	// - title-cased
	// - title-cased and then printed with %q
	// - printed with %q and then title-cased.
	const templateText = `
Input: {{printf "%q" .}}
Output 0: {{title .}}
Output 1: {{title . | printf "%q"}}
Output 2: {{printf "%q" . | title}}
`

	// Create a template, add the function map, and parse the text.
	tmpl, err := template.New("titleTest").Funcs(funcMap).Parse(templateText)
	if err != nil {
		log.Fatalf("parsing: %s", err)
	}

	// Run the template to verify the output.
	err = tmpl.Execute(os.Stdout, "the go programming language")
	if err != nil {
		log.Fatalf("execution: %s", err)
	}

}
Output:
Input: "the go programming language"
Output 0: The Go Programming Language
Output 1: "The Go Programming Language"
Output 2: "The Go Programming Language"
Example (Glob)

Here we demonstrate loading a set of templates from a directory.

package main

import (
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"

	"github.com/jocgir/template"
)

// templateFile defines the contents of a template to be stored in a file, for testing.
type templateFile struct {
	name     string
	contents string
}

func createTestDir(files []templateFile) string {
	dir, err := ioutil.TempDir("", "template")
	if err != nil {
		log.Fatal(err)
	}
	for _, file := range files {
		f, err := os.Create(filepath.Join(dir, file.name))
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		_, err = io.WriteString(f, file.contents)
		if err != nil {
			log.Fatal(err)
		}
	}
	return dir
}

func main() {
	// Here we create a temporary directory and populate it with our sample
	// template definition files; usually the template files would already
	// exist in some location known to the program.
	dir := createTestDir([]templateFile{
		// T0.tmpl is a plain template file that just invokes T1.
		{"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`},
		// T1.tmpl defines a template, T1 that invokes T2.
		{"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
		// T2.tmpl defines a template T2.
		{"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
	})
	// Clean up after the test; another quirk of running as an example.
	defer os.RemoveAll(dir)

	// pattern is the glob pattern used to find all the template files.
	pattern := filepath.Join(dir, "*.tmpl")

	// Here starts the example proper.
	// T0.tmpl is the first name matched, so it becomes the starting template,
	// the value returned by ParseGlob.
	tmpl := template.Must(template.ParseGlob(pattern))

	err := tmpl.Execute(os.Stdout, nil)
	if err != nil {
		log.Fatalf("template execution: %s", err)
	}
}
Output:
T0 invokes T1: (T1 invokes T2: (This is T2))
Example (Helpers)

This example demonstrates one way to share some templates and use them in different contexts. In this variant we add multiple driver templates by hand to an existing bundle of templates.

package main

import (
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"

	"github.com/jocgir/template"
)

// templateFile defines the contents of a template to be stored in a file, for testing.
type templateFile struct {
	name     string
	contents string
}

func createTestDir(files []templateFile) string {
	dir, err := ioutil.TempDir("", "template")
	if err != nil {
		log.Fatal(err)
	}
	for _, file := range files {
		f, err := os.Create(filepath.Join(dir, file.name))
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		_, err = io.WriteString(f, file.contents)
		if err != nil {
			log.Fatal(err)
		}
	}
	return dir
}

func main() {
	// Here we create a temporary directory and populate it with our sample
	// template definition files; usually the template files would already
	// exist in some location known to the program.
	dir := createTestDir([]templateFile{
		// T1.tmpl defines a template, T1 that invokes T2.
		{"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
		// T2.tmpl defines a template T2.
		{"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
	})
	// Clean up after the test; another quirk of running as an example.
	defer os.RemoveAll(dir)

	// pattern is the glob pattern used to find all the template files.
	pattern := filepath.Join(dir, "*.tmpl")

	// Here starts the example proper.
	// Load the helpers.
	templates := template.Must(template.ParseGlob(pattern))
	// Add one driver template to the bunch; we do this with an explicit template definition.
	_, err := templates.Parse("{{define `driver1`}}Driver 1 calls T1: ({{template `T1`}})\n{{end}}")
	if err != nil {
		log.Fatal("parsing driver1: ", err)
	}
	// Add another driver template.
	_, err = templates.Parse("{{define `driver2`}}Driver 2 calls T2: ({{template `T2`}})\n{{end}}")
	if err != nil {
		log.Fatal("parsing driver2: ", err)
	}
	// We load all the templates before execution. This package does not require
	// that behavior but html/template's escaping does, so it's a good habit.
	err = templates.ExecuteTemplate(os.Stdout, "driver1", nil)
	if err != nil {
		log.Fatalf("driver1 execution: %s", err)
	}
	err = templates.ExecuteTemplate(os.Stdout, "driver2", nil)
	if err != nil {
		log.Fatalf("driver2 execution: %s", err)
	}
}
Output:
Driver 1 calls T1: (T1 invokes T2: (This is T2))
Driver 2 calls T2: (This is T2)
Example (Share)

This example demonstrates how to use one group of driver templates with distinct sets of helper templates.

package main

import (
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"

	"github.com/jocgir/template"
)

// templateFile defines the contents of a template to be stored in a file, for testing.
type templateFile struct {
	name     string
	contents string
}

func createTestDir(files []templateFile) string {
	dir, err := ioutil.TempDir("", "template")
	if err != nil {
		log.Fatal(err)
	}
	for _, file := range files {
		f, err := os.Create(filepath.Join(dir, file.name))
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		_, err = io.WriteString(f, file.contents)
		if err != nil {
			log.Fatal(err)
		}
	}
	return dir
}

func main() {
	// Here we create a temporary directory and populate it with our sample
	// template definition files; usually the template files would already
	// exist in some location known to the program.
	dir := createTestDir([]templateFile{
		// T0.tmpl is a plain template file that just invokes T1.
		{"T0.tmpl", "T0 ({{.}} version) invokes T1: ({{template `T1`}})\n"},
		// T1.tmpl defines a template, T1 that invokes T2. Note T2 is not defined
		{"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
	})
	// Clean up after the test; another quirk of running as an example.
	defer os.RemoveAll(dir)

	// pattern is the glob pattern used to find all the template files.
	pattern := filepath.Join(dir, "*.tmpl")

	// Here starts the example proper.
	// Load the drivers.
	drivers := template.Must(template.ParseGlob(pattern))

	// We must define an implementation of the T2 template. First we clone
	// the drivers, then add a definition of T2 to the template name space.

	// 1. Clone the helper set to create a new name space from which to run them.
	first, err := drivers.Clone()
	if err != nil {
		log.Fatal("cloning helpers: ", err)
	}
	// 2. Define T2, version A, and parse it.
	_, err = first.Parse("{{define `T2`}}T2, version A{{end}}")
	if err != nil {
		log.Fatal("parsing T2: ", err)
	}

	// Now repeat the whole thing, using a different version of T2.
	// 1. Clone the drivers.
	second, err := drivers.Clone()
	if err != nil {
		log.Fatal("cloning drivers: ", err)
	}
	// 2. Define T2, version B, and parse it.
	_, err = second.Parse("{{define `T2`}}T2, version B{{end}}")
	if err != nil {
		log.Fatal("parsing T2: ", err)
	}

	// Execute the templates in the reverse order to verify the
	// first is unaffected by the second.
	err = second.ExecuteTemplate(os.Stdout, "T0.tmpl", "second")
	if err != nil {
		log.Fatalf("second execution: %s", err)
	}
	err = first.ExecuteTemplate(os.Stdout, "T0.tmpl", "first")
	if err != nil {
		log.Fatalf("first: execution: %s", err)
	}

}
Output:
T0 (second version) invokes T1: (T1 invokes T2: (T2, version B))
T0 (first version) invokes T1: (T1 invokes T2: (T2, version A))

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) *Template

New allocates a new, undefined template with the given name.

func ParseFiles

func ParseFiles(filenames ...string) (*Template, error)

ParseFiles creates a new Template and parses the template definitions from the named files. The returned template's name will have the base name and parsed contents of the first file. There must be at least one file. If an error occurs, parsing stops and the returned *Template is nil.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results. For instance, ParseFiles("a/foo", "b/foo") stores "b/foo" as the template named "foo", while "a/foo" is unavailable.

func ParseGlob

func ParseGlob(pattern string) (*Template, error)

ParseGlob creates a new Template and parses the template definitions from the files identified by the pattern. The files are matched according to the semantics of filepath.Match, and the pattern must match at least one file. The returned template will have the (base) name and (parsed) contents of the first file matched by the pattern. ParseGlob is equivalent to calling ParseFiles with the list of files matched by the pattern.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

func (*Template) AddParseTree

func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)

AddParseTree associates the argument parse tree with the template t, giving it the specified name. If the template has not been defined, this tree becomes its definition. If it has been defined and already has that name, the existing definition is replaced; otherwise a new template is created, defined, and returned.

func (*Template) Clone

func (t *Template) Clone() (*Template, error)

Clone returns a duplicate of the template, including all associated templates. The actual representation is not copied, but the name space of associated templates is, so further calls to Parse in the copy will add templates to the copy but not to the original. Clone can be used to prepare common templates and use them with variant definitions for other templates by adding the variants after the clone is made.

func (*Template) DefinedTemplates

func (t *Template) DefinedTemplates() string

DefinedTemplates returns a string listing the defined templates, prefixed by the string "; defined templates are: ". If there are none, it returns the empty string. For generating an error message here and in html/template.

func (*Template) Delims

func (t *Template) Delims(left, right string) *Template

Delims sets the action delimiters to the specified strings, to be used in subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template definitions will inherit the settings. An empty delimiter stands for the corresponding default: {{ or }}. The return value is the template, so calls can be chained.

func (*Template) ErrorManagers added in v1.14.1

func (t *Template) ErrorManagers(name string, managers ...*ErrorManager) *Template

ErrorManagers allows registration of error handlers to manage errors. An error handler is a packaged error handler function with preset filters for mode and source.

Is is possible to deregister a previously added error manager by simply calling this method with the id of the manager to remove without managers.

t.ErrorManagers("id to remove")
Example (Bad_parameters)
package main

import (
	"bytes"
	"fmt"
	"strconv"

	"github.com/jocgir/template"
)

func main() {
	var (
		withErrorManager bool

		add  = func(a, b int) int { return a + b }
		base = template.New("test").Funcs(template.FuncMap{"add": add})
		test = func(code string) {
			t := template.Must(base.Clone())
			if withErrorManager {
				// We register an handler to add arguments if they are not integer or there are
				// more or less arguments than expected
				t.ErrorManagers("Add other types", template.NewErrorManager(
					func(context *template.Context) (result interface{}, action template.ErrorAction) {
						context.ClearError()
						args := context.EvalArgs()

						defer func() {
							if recover() != nil {
								// In case of error, we simply concat the string representation of args.
								result = fmt.Sprint(args...)
								action = template.ResultReplaced
							}
						}()

						// We try to add all arguments as float64
						var value float64
						for _, arg := range args {
							v, err := strconv.ParseFloat(fmt.Sprint(arg), 64)
							if err != nil {
								panic(err)
							}
							value += v
						}
						return value, template.ResultReplaced
					}).
					OnMembers("add").
					Filters(`(?P<template>.*):(?P<line>\d+):(?P<column>\d+): executing .*: (?P<error>.*)$`),
				)
			}
			var buffer = new(bytes.Buffer)
			err := template.Must(t.Parse(code)).Execute(buffer, nil)
			result := buffer.String()
			if err != nil {
				result = err.Error()
			}
			fmt.Printf("  %s = %q\n", code, result)
		}
	)

	for _, mode := range []string{"Without", "With"} {
		withErrorManager = mode == "With"
		fmt.Printf("\n%s Error Manager:\n", mode)
		test(`{{ add 2 3 }}`)
		test(`{{ add 2.0 3.0 }}`)
		test(`{{ add }}`)
		test(`{{ add 5 }}`)
		test(`{{ add 1 2 3 }}`)
		test(`{{ add 1.2 3.4 }}`)
		test(`{{ add "a" "b" "c" "d" }}`)
		test(`{{ "suffix" | add "prefix" 0 1 }}`)
	}

}
Output:
	Without Error Manager:
  {{ add 2 3 }} = "5"
  {{ add 2.0 3.0 }} = "5"
  {{ add }} = "template: test:1:3: executing \"test\" at <add>: wrong number of args for add: want 2 got 0"
  {{ add 5 }} = "template: test:1:3: executing \"test\" at <add>: wrong number of args for add: want 2 got 1"
  {{ add 1 2 3 }} = "template: test:1:3: executing \"test\" at <add>: wrong number of args for add: want 2 got 3"
  {{ add 1.2 3.4 }} = "template: test:1:7: executing \"test\" at <1.2>: expected integer; found 1.2"
  {{ add "a" "b" "c" "d" }} = "template: test:1:3: executing \"test\" at <add>: wrong number of args for add: want 2 got 4"
  {{ "suffix" | add "prefix" 0 1 }} = "template: test:1:14: executing \"test\" at <add>: wrong number of args for add: want 2 got 4"

With Error Manager:
  {{ add 2 3 }} = "5"
  {{ add 2.0 3.0 }} = "5"
  {{ add }} = "0"
  {{ add 5 }} = "5"
  {{ add 1 2 3 }} = "6"
  {{ add 1.2 3.4 }} = "4.6"
  {{ add "a" "b" "c" "d" }} = "abcd"
  {{ "suffix" | add "prefix" 0 1 }} = "prefix0 1suffix"
Example (Format)
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"reflect"

	"github.com/divan/num2words"
	"github.com/jocgir/template"
)

func main() {
	t, err := template.New("test").
		// We register new functions to return a number, a list and a map
		ExtraFuncs(
			template.FuncMap{
				"number": func() int { return 1234 },
				"list":   func() (int, string) { return 0, "Zero" },
				"map":    func() template.Map { return template.Map{"hello": "world"} },
			}).

		// We register an error manager to convert render list into json (map should not be affected)
		ErrorManagers("List as json", template.NewErrorManager(
			func(context *template.Context) (interface{}, template.ErrorAction) {
				result, err := json.MarshalIndent(context.Result().Interface(), "", "  ")
				if err != nil {
					context.SetError(err)
				}
				return string(result), template.ResultReplaced
			}).OnSources(template.Print).OnKinds(reflect.Array, reflect.Slice)).

		// Weird example, but we also convert integer value into its english representation
		// using github.com/divan/num2words package
		ErrorManagers("Number as text", template.NewErrorManager(
			func(context *template.Context) (interface{}, template.ErrorAction) {
				value := context.Result().Int()
				return num2words.ConvertAnd(int(value)), template.ResultReplaced
			}).OnSources(template.Print).OnKinds(reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64)).

		// Here is the template text to process
		Parse("Number = {{number}}\nList = {{list}}\nMap = {{map}}")
	if err != nil {
		panic(err)
	}

	buffer := new(bytes.Buffer)
	t.Execute(buffer, nil)
	fmt.Println(buffer)
}
Output:
Number = one thousand two hundred and thirty-four
List = [
  0,
  "Zero"
]
Map = map[hello:world]

func (*Template) Execute

func (t *Template) Execute(wr io.Writer, data interface{}) error

Execute applies a parsed template to the specified data object, and writes the output to wr. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer. A template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

If data is a reflect.Value, the template applies to the concrete value that the reflect.Value holds, as in fmt.Print.

func (*Template) ExecuteTemplate

func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error

ExecuteTemplate applies the template associated with t that has the given name to the specified data object and writes the output to wr. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer. A template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

func (*Template) ExtraFuncs added in v1.14.1

func (t *Template) ExtraFuncs(funcMap FuncMap) *Template

ExtraFuncs allows registering of non standard functions, i.e. functions with no return, or that returns multiple values.

Using this method to register your functions also handle calling object methods that are either not returning values or return more that one value.

Functions with no return will be modified to return an empty string. Functions with more than one return value will be modified to return an array of interface{}. Functions with just an error value will be modified to return an empty string if there is no error.

Example (Functions)
package main

import (
	"bytes"
	"fmt"

	"github.com/jocgir/template"
)

func main() {
	var (
		usingExtra bool

		test = func(name, code string, fun interface{}) {
			var (
				buffer = new(bytes.Buffer)
				t      = template.New("test").Option(template.Trap)
				funcs  = template.FuncMap{name: fun}
				result string
			)

			defer func() {
				if rec := recover(); rec != nil {
					result = rec.(error).Error()
				}
				fmt.Printf("  %s = %q\n", code, result)
			}()

			if usingExtra {
				t.ExtraFuncs(funcs)
			} else {
				t.Funcs(funcs)
			}

			t = template.Must(t.Parse(code))
			if err := t.Execute(buffer, nil); err == nil {
				result = buffer.String()
			} else {
				result = err.Error()
			}
		}
	)

	for _, mode := range []string{"Funcs", "ExtraFuncs"} {
		usingExtra = mode == "ExtraFuncs"
		fmt.Printf("\nWith %s:\n", mode)
		test("empty", `{{empty}}`, func() {})
		test("tuple", `{{tuple}}`, func() (int, int) { return 1, 2 })
		test("error", `{{error}}`, func() error { return fmt.Errorf("bang") })
		test("ok", `{{trap ok}}`, func() (string, error) { return "Hello", nil })
		test("error", `{{trap error}}`, func() (string, error) { panic("Boom!") })
	}

}
Output:
With Funcs:
  {{empty}} = "can't install method/function \"empty\" with 0 results"
  {{tuple}} = "can't install method/function \"tuple\" with 2 results"
  {{error}} = "can't install method/function \"error\" with only error as result"
  {{trap ok}} = "Hello"
  {{trap error}} = "<no value>"

With ExtraFuncs:
  {{empty}} = ""
  {{tuple}} = "[1 2]"
  {{error}} = "template: test:1:2: executing \"test\" at <error>: bang"
  {{trap ok}} = "Hello"
  {{trap error}} = "<no value>"

func (*Template) Funcs

func (t *Template) Funcs(funcMap FuncMap) *Template

Funcs adds the elements of the argument map to the template's function map. It must be called before the template is parsed. It panics if a value in the map is not a function with appropriate return type or if the name cannot be used syntactically as a function in a template. It is legal to overwrite elements of the map. The return value is the template, so calls can be chained.

Example (Context)
package main

import (
	"bytes"
	"fmt"
	"strconv"

	"github.com/jocgir/template"
)

func main() {
	var (
		t = template.New("test")

		// Adding a custom function that directly handle the *template.Context greatly simplifies
		// the code and avoid having to handle errors. The custom function is then responsible to
		// evaluate the supplied arguments.
		sum = func(context *template.Context) interface{} {
			var (
				value float64
				args  = context.EvalArgs()
			)
			for _, arg := range args {
				v, err := strconv.ParseFloat(fmt.Sprint(arg), 64)
				if err != nil {
					return fmt.Sprint(args...)
				}
				value += v
			}
			return value
		}

		test = func(code string) {
			var (
				buffer = new(bytes.Buffer)
				result string
			)

			if err := template.Must(t.Parse(code)).Execute(buffer, nil); err == nil {
				result = buffer.String()
			} else {
				result = err.Error()
			}
			fmt.Printf("%s = %q\n", code, result)
		}
	)

	// There is no need to call ExtraFuncs when the custom function already handle *template.Context
	t.Funcs(template.FuncMap{"sum": sum})

	test(`{{ sum 2 3 }}`)
	test(`{{ sum 2.0 3.0 }}`)
	test(`{{ sum }}`)
	test(`{{ sum 5 }}`)
	test(`{{ sum 1 2 3 }}`)
	test(`{{ sum 1.2 3.4 }}`)
	test(`{{ sum "a" "b" "c" "d" }}`)
	test(`{{ "suffix" | sum "prefix" 0 1 }}`)

}
Output:
{{ sum 2 3 }} = "5"
{{ sum 2.0 3.0 }} = "5"
{{ sum }} = "0"
{{ sum 5 }} = "5"
{{ sum 1 2 3 }} = "6"
{{ sum 1.2 3.4 }} = "4.6"
{{ sum "a" "b" "c" "d" }} = "abcd"
{{ "suffix" | sum "prefix" 0 1 }} = "prefix0 1suffix"

func (*Template) GetBuiltins added in v1.14.1

func (t *Template) GetBuiltins() []string

GetBuiltins returns the sorted list of builtin functions name added to the template.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/jocgir/template"
)

func main() {
	builtins := template.New("test").GetBuiltins()
	fmt.Println(strings.Join(builtins, "\n"))

}
Output:
and
call
eq
ge
gt
html
index
js
le
len
lt
ne
not
or
print
printf
println
slice
urlquery

func (*Template) GetBuiltinsMap added in v1.14.1

func (t *Template) GetBuiltinsMap() FuncMap

GetBuiltinsMap returns the list of builtin functions added to the template.

func (*Template) GetFuncs

func (t *Template) GetFuncs() []string

GetFuncs returns the sorted list of function names added to the template.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/jocgir/template"
)

func main() {
	funcs := template.New("test").
		Funcs(template.FuncMap{
			"hello": func() string { return "Hello" },
			"world": func() string { return "world" },
		}).
		GetFuncs()
	fmt.Println(strings.Join(funcs, "\n"))

}
Output:
hello
world

func (*Template) GetFuncsMap added in v1.14.1

func (t *Template) GetFuncsMap() FuncMap

GetFuncsMap returns the list of function added to the template.

func (*Template) Lookup

func (t *Template) Lookup(name string) *Template

Lookup returns the template with the given name that is associated with t. It returns nil if there is no such template or the template has no definition.

func (*Template) MissingMode added in v1.14.2

func (t *Template) MissingMode() MissingAction

MissingMode returns the missing action mode currently set on template.

func (*Template) Name

func (t *Template) Name() string

Name returns the name of the template.

func (*Template) New

func (t *Template) New(name string) *Template

New allocates a new, undefined template associated with the given one and with the same delimiters. The association, which is transitive, allows one template to invoke another with a {{template}} action.

Because associated templates share underlying data, template construction cannot be done safely in parallel. Once the templates are constructed, they can be executed in parallel.

func (*Template) Option

func (t *Template) Option(options ...interface{}) *Template

Option sets options for the template. Options can be designed by strings as in OptionDeprecated or they can set by providing one of MissingAction value:

template.Option(template.Default)
template.Option(template.Error)
template.Option(template.ZeroValue)
template.Option(template.Invalid)
// You can still use the previous way of specifying options
template.Option("missingkey=zero")

You can also provide other options to enable extended template features:

template.Option(template.FunctionsAsMethods)
template.Option(template.FunctionsWithContext)
template.Option(template.NonStandardResults)
template.Option(template.Trap)
template.Option(template.Eval)

Many options can be specified at once:

template.Option(tenplate.ZeroValue, template.Trap, template.Eval)
// Compatible types can also be combined with logical or
template.Option(tenplate.ZeroValue, template.Trap | template.Eval)
// It is also possible to enable all extended features at once
template.Option(tenplate.Default, template.AllOptions)
Example (Flow_control)
package main

import (
	"bytes"
	"fmt"

	"github.com/jocgir/template"
)

func main() {
	test := func(flowAction, test, code string) {
		var (
			result string
			buffer = new(bytes.Buffer)

			sequence = func(n int) []int {
				result := make([]int, n)
				for i := range result {
					result[i] = i + 1
				}
				return result
			}

			t = template.Must(template.New("test").
				Option(template.FlowControl).
				Funcs(template.FuncMap{"seq": sequence}).
				Parse(fmt.Sprintf(code, test, flowAction)))
		)

		if err := t.Execute(buffer, nil); err == nil {
			result = buffer.String()
		} else {
			result = err.Error()
		}
		fmt.Println(result)
	}

	code := `
		{{- "List with %[2]s on value %[1]s 5: " -}}
		{{- range $i, $value := seq 10 -}}
			{{- if $i }}-{{ end -}}
			{{- if %[1]s $value 5 }}{{ %[2]s }}{{- end -}}
			{{ $value }}
		{{- end -}}
		{{- " That's all Folks!" -}}
	`
	test("break", "gt", code)
	test("continue", "le", code)
	test("return", "eq", code)

}
Output:
List with break on value gt 5: 1-2-3-4-5- That's all Folks!
List with continue on value le 5: -----6-7-8-9-10 That's all Folks!
List with return on value eq 5: 1-2-3-4-
Example (Functions_as_methods)
package main

import (
	"bytes"
	"fmt"
	"strconv"
	"strings"

	"github.com/jocgir/template"
)

func main() {
	var (
		t = template.New("test")

		// Remove all strings representation of arguments from the first argument
		remove = func(context *template.Context) interface{} {
			var (
				args   = context.EvalArgs()
				result = fmt.Sprint(args[0])
			)
			for _, substr := range args[1:] {
				result = strings.ReplaceAll(result, fmt.Sprint(substr), "")
			}
			return result
		}

		substract = func(context *template.Context) interface{} {
			var (
				value float64
				args  = context.EvalArgs()
			)
			for i, arg := range args {
				v, err := strconv.ParseFloat(fmt.Sprint(arg), 64)
				if err != nil {
					// If one onf the value is not numeric, we consider delegate the
					// processing to the remove function
					return context.Call("remove")
				}
				if i > 0 {
					v = -v
				}
				value += v
			}
			return value
		}

		test = func(code string) {
			var (
				buffer = new(bytes.Buffer)
				result string
			)

			if err := template.Must(t.Parse(code)).Execute(buffer, nil); err == nil {
				result = buffer.String()
			} else {
				result = err.Error()
			}
			fmt.Printf("  %s = %q\n", code, result)
		}
	)

	// There is no need to call ExtraFuncs when the custom function already handle *template.Context
	t.Funcs(template.FuncMap{
		"remove":    remove,
		"substract": substract,
	}).Option(template.FunctionsAsMethods)

	t.Option()
	for _, mode := range []string{"registered", "unregistered"} {
		fmt.Println("\nMethods as Functions is", mode)
		if mode == "unregistered" {
			// We deregister the error manager that handle the method as function mechanism
			t.ErrorManagers(template.FuncsAsMethodsID)
		}

		test(`{{ (2).substract 3 }}`)
		test(`{{ (2.0).substract 3.0 }}`)
		test(`{{ (5).substract }}`)
		test(`{{ (1).substract 2 3 }}`)
		test(`{{ (1.2).substract 3.4 }}`)
		test(`{{ ((1.2).substract 3.4).substract 5.6 }}`)
		test(`{{ ("Hello").substract "a" "e" "i" "o" "u" }}`)
		test(`{{ "!" | ("Hello World!").substract "ll" }}`)
		test(`Not working: {{ (2).add 3 }}`)
	}

}
Output:
Methods as Functions is registered
  {{ (2).substract 3 }} = "-1"
  {{ (2.0).substract 3.0 }} = "-1"
  {{ (5).substract }} = "5"
  {{ (1).substract 2 3 }} = "-4"
  {{ (1.2).substract 3.4 }} = "-2.2"
  {{ ((1.2).substract 3.4).substract 5.6 }} = "-7.8"
  {{ ("Hello").substract "a" "e" "i" "o" "u" }} = "Hll"
  {{ "!" | ("Hello World!").substract "ll" }} = "Heo World"
  Not working: {{ (2).add 3 }} = "template: test:1:17: executing \"test\" at <2>: can't evaluate field add in type int"

Methods as Functions is unregistered
  {{ (2).substract 3 }} = "template: test:1:4: executing \"test\" at <2>: can't evaluate field substract in type int"
  {{ (2.0).substract 3.0 }} = "template: test:1:4: executing \"test\" at <2.0>: can't evaluate field substract in type float64"
  {{ (5).substract }} = "template: test:1:4: executing \"test\" at <5>: can't evaluate field substract in type int"
  {{ (1).substract 2 3 }} = "template: test:1:4: executing \"test\" at <1>: can't evaluate field substract in type int"
  {{ (1.2).substract 3.4 }} = "template: test:1:4: executing \"test\" at <1.2>: can't evaluate field substract in type float64"
  {{ ((1.2).substract 3.4).substract 5.6 }} = "template: test:1:5: executing \"test\" at <1.2>: can't evaluate field substract in type float64"
  {{ ("Hello").substract "a" "e" "i" "o" "u" }} = "template: test:1:4: executing \"test\" at <\"Hello\">: can't evaluate field substract in type string"
  {{ "!" | ("Hello World!").substract "ll" }} = "template: test:1:10: executing \"test\" at <\"Hello World!\">: can't evaluate field substract in type string"
  Not working: {{ (2).add 3 }} = "template: test:1:17: executing \"test\" at <2>: can't evaluate field add in type int"
Example (Methods)
package main

import (
	"bytes"
	"fmt"

	"github.com/jocgir/template"
)

func main() {
	// Let's say we have the following object as context:
	//   type MyObject struct{}
	//   func (o *MyObject) NoReturn()         {}
	//   func (o *MyObject) Error() error      { return fmt.Errorf("bang") }
	//   func (o *MyObject) Tuple() (int, int) { return 1, 2 }

	var (
		withExtraFuncs bool

		test = func(code string) {
			var (
				buffer = new(bytes.Buffer)
				t      = template.New("test")
				result string
			)

			defer func() {
				if rec := recover(); rec != nil {
					result = rec.(error).Error()
				}
				fmt.Printf("  %s = %q\n", code, result)
			}()

			if withExtraFuncs {
				// Calling ExtraFuncs with or without custom functions registers
				// special functions/methods error handling and also add trap and eval
				// functions.
				t.Option(template.NonStandardResults, template.Trap)
			}
			tt := template.Must(t.Parse(code))
			if err := tt.Execute(buffer, new(MyObject)); err == nil {
				result = buffer.String()
			} else {
				result = err.Error()
			}
		}
	)

	for _, mode := range []string{"Without", "With"} {
		withExtraFuncs = mode == "With"
		fmt.Printf("\n%s ExtraFuncs:\n", mode)
		test(`{{ .NoReturn }}`)
		test(`{{ .Tuple }}`)
		test(`{{ .Error }}`)
		test(`{{ if trap .Error }}OK{{ else }}Error: {{ $error }}{{ end }}`)
	}

}

type MyObject struct{}

func (o *MyObject) NoReturn()         {}
func (o *MyObject) Error() error      { return fmt.Errorf("bang") }
func (o *MyObject) Tuple() (int, int) { return 1, 2 }
Output:
Without ExtraFuncs:
  {{ .NoReturn }} = "template: test:1:3: executing \"test\" at <.NoReturn>: can't call method/function \"NoReturn\" with 0 results"
  {{ .Tuple }} = "template: test:1:3: executing \"test\" at <.Tuple>: can't call method/function \"Tuple\" with 2 results"
  {{ .Error }} = "template: test:1:3: executing \"test\" at <.Error>: can't call method/function \"Error\" with 1 results"
  {{ if trap .Error }}OK{{ else }}Error: {{ $error }}{{ end }} = "template: test:1: function \"trap\" not defined"

With ExtraFuncs:
  {{ .NoReturn }} = ""
  {{ .Tuple }} = "[1 2]"
  {{ .Error }} = "template: test:1:3: executing \"test\" at <.Error>: bang"
  {{ if trap .Error }}OK{{ else }}Error: {{ $error }}{{ end }} = "Error: bang"
Example (Trap)
package main

import (
	"bytes"
	"fmt"

	"github.com/jocgir/template"
)

func main() {
	test := func(code string) {
		var (
			result string
			buffer = new(bytes.Buffer)

			divide = func(a, b float64) float64 {
				if b == 0 {
					panic("Divide by 0")
				}
				return a / b
			}

			t = template.Must(template.New("test").
				Option(template.Trap).
				Funcs(template.FuncMap{"div": divide}).
				Parse(code))
		)

		if err := t.Execute(buffer, nil); err == nil {
			result = buffer.String()
		} else {
			result = err.Error()
		}
		fmt.Printf("%s = %q\n", code, result)
	}

	test(`{{ div 1 2 }}`)
	test(`{{ div 2 0 }}`)
	test(`{{ trap }}`)
	test(`{{ trap (div 1 2) (div 6 3) }}`)
	test(`{{ trap (div 1 2) (div 2 0) }} Status: {{$error}}`)
	test(`{{ with trap (div 9 4) }}{{ . }}{{ else }}Error: {{ $error }}{{ end }}`)
	test(`{{ with trap (div 3 0) }}{{ . }}{{ else }}Error: {{ $error }}{{ end }}`)

}
Output:
{{ div 1 2 }} = "0.5"
{{ div 2 0 }} = "template: test:1:3: executing \"test\" at <div 2 0>: error calling div: Divide by 0"
{{ trap }} = ""
{{ trap (div 1 2) (div 6 3) }} = "[0.5 2]"
{{ trap (div 1 2) (div 2 0) }} Status: {{$error}} = "<no value> Status: Divide by 0"
{{ with trap (div 9 4) }}{{ . }}{{ else }}Error: {{ $error }}{{ end }} = "2.25"
{{ with trap (div 3 0) }}{{ . }}{{ else }}Error: {{ $error }}{{ end }} = "Error: Divide by 0"

func (*Template) OptionDeprecated added in v1.14.2

func (t *Template) OptionDeprecated(opt ...string) *Template

OptionDeprecated sets options for the template. Options are described by strings, either a simple string or "key=value". There can be at most one equals sign in an option string. If the option string is unrecognized or otherwise invalid, Option panics.

Known options:

missingkey: Control the behavior during execution if a map is indexed with a key that is not present in the map.

"missingkey=default" or "missingkey=invalid"
	The default behavior: Do nothing and continue execution.
	If printed, the result of the index operation is the string
	"<no value>".
"missingkey=zero"
	The operation returns the zero value for the map type's element.
"missingkey=error"
	Execution stops immediately with an error.

func (*Template) Parse

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

Parse parses text as a template body for t. Named template definitions ({{define ...}} or {{block ...}} statements) in text define additional templates associated with t and are removed from the definition of t itself.

Templates can be redefined in successive calls to Parse. A template definition with a body containing only white space and comments is considered empty and will not replace an existing template's body. This allows using Parse to add new named template definitions without overwriting the main template body.

func (*Template) ParseFiles

func (t *Template) ParseFiles(filenames ...string) (*Template, error)

ParseFiles parses the named files and associates the resulting templates with t. If an error occurs, parsing stops and the returned template is nil; otherwise it is t. There must be at least one file. Since the templates created by ParseFiles are named by the base names of the argument files, t should usually have the name of one of the (base) names of the files. If it does not, depending on t's contents before calling ParseFiles, t.Execute may fail. In that case use t.ExecuteTemplate to execute a valid template.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

func (*Template) ParseGlob

func (t *Template) ParseGlob(pattern string) (*Template, error)

ParseGlob parses the template definitions in the files identified by the pattern and associates the resulting templates with t. The files are matched according to the semantics of filepath.Match, and the pattern must match at least one file. ParseGlob is equivalent to calling t.ParseFiles with the list of files matched by the pattern.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

func (*Template) Templates

func (t *Template) Templates() []*Template

Templates returns a slice of defined templates associated with t.

Directories

Path Synopsis
Package fmtsort provides a general stable ordering mechanism for maps, on behalf of the fmt and text/template packages.
Package fmtsort provides a general stable ordering mechanism for maps, on behalf of the fmt and text/template packages.
Package parse builds parse trees for templates as defined by text/template and html/template.
Package parse builds parse trees for templates as defined by text/template and html/template.

Jump to

Keyboard shortcuts

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