Involved Source Files
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 white
space, all trailing white space is trimmed from the immediately preceding text.
Similarly, if the right delimiter ("}}") is preceded by white space and a minus
sign, all leading white space is trimmed from the immediately following text.
In these trim markers, the white space must be present:
"{{- 3}}" is like "{{3}}" but trims the immediately preceding text, while
"{{-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)
}
exec.gofuncs.gohelper.gooption.gotemplate.go
Code Examples
package main
import (
"log"
"os"
"text/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)
}
}
}
package main
import (
"log"
"os"
"strings"
"text/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)
}
}
Package-Level Type Names (total 11, in which 3 are exported)
/* sort exporteds by: | */
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.)
// Pre-formatted error.
// Name of template.
( T) Error() string( T) Unwrap() error
T : error
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.
func builtins() FuncMap
func (*Template).Funcs(funcMap FuncMap) *Template
func github.com/spf13/cobra.AddTemplateFuncs(tmplFuncs FuncMap)
func addFuncs(out, in FuncMap)
func addValueFuncs(out map[string]reflect.Value, in FuncMap)
func createValueFuncs(funcMap FuncMap) map[string]reflect.Value
var github.com/manifoldco/promptui.FuncMap
var github.com/spf13/cobra.templateFuncs
var html/template.funcMap
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.
Tree*parse.Tree
// parsing mode.
// name of the top-level template during parsing, for error messages.
// top-level root of the tree.
common*commoncommon.execFuncsmap[string]reflect.Value
We use two maps, one for parsing and one for execution.
This separation makes the API cleaner since it doesn't
expose reflection to the client.
// protects parseFuncs and execFuncs
common.optionoptioncommon.parseFuncsFuncMap
// Map from name to defined templates.
leftDelimstringnamestringrightDelimstring
// line of left delim starting action
Parsing only; cleared after parse.
Tree.lex*parse.lexerTree.modeparse.ModeTree.peekCountint
// text parsed to create the template (or its parent)
// three-token lookahead for parser.
Tree.treeSetmap[string]*parse.Tree
// variables defined at the moment.
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.
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.
Copy returns a copy of the Tree. Any parsing state is discarded.
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.
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.
ErrorContext returns a textual representation of the location of the node in the input text.
The receiver is only used when the node does not have a pointer to the tree inside,
which can occur in old code.
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.
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.
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.
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.
Name returns the name of the 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.
Option 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.
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.
ParseFS is like ParseFiles or ParseGlob but reads from the file system fsys
instead of the host operating system's file system.
It accepts a list of glob patterns.
(Note that most file names serve as glob patterns matching only themselves.)
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.
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.
Templates returns a slice of defined templates associated with t.
Action:
control
command ("|" command)*
Left delim is past. Now get actions.
First word could be a keyword such as range.
add adds tree to t.treeSet.
associate installs the new template into the group of templates associated
with t. The two are already known to share the common structure.
The boolean return value reports whether to store this tree as t.Tree.
backup backs the input stream up one token.
backup2 backs the input stream up two tokens.
The zeroth token is already there.
backup3 backs the input stream up three tokens
The zeroth token is already there.
Block:
{{block stringValue pipeline}}
Block keyword is past.
The name must be something that can evaluate to a string.
The pipeline is mandatory.
( T) checkPipeline(pipe *parse.PipeNode, context string)( T) clearActionLine()
command:
operand (space operand)*
space-separated arguments up to a pipeline character or right delimiter.
we consume the pipe character but leave the right delim to terminate the action.
copy returns a shallow copy of t, with common set to the argument.
Else:
{{else}}
Else keyword is past.
End:
{{end}}
End keyword is past.
error terminates processing.
errorf formats the error and terminates processing.
(*T) execute(wr io.Writer, data interface{}) (err error)
expect consumes the next token and guarantees it has the required type.
expectOneOf consumes the next token and guarantees it has one of the required types.
hasFunction reports if a function name exists in the Tree's maps.
If:
{{if pipeline}} itemList {{end}}
{{if pipeline}} itemList {{else}} itemList {{end}}
If keyword is past.
init guarantees that t has a valid common structure.
itemList:
textOrAction*
Terminates at {{end}} or {{else}}, returned separately.
( T) newAction(pos parse.Pos, line int, pipe *parse.PipeNode) *parse.ActionNode( T) newBool(pos parse.Pos, true bool) *parse.BoolNode( T) newChain(pos parse.Pos, node parse.Node) *parse.ChainNode( T) newCommand(pos parse.Pos) *parse.CommandNode( T) newComment(pos parse.Pos, text string) *parse.CommentNode( T) newDot(pos parse.Pos) *parse.DotNode( T) newElse(pos parse.Pos, line int) *parse.elseNode( T) newEnd(pos parse.Pos) *parse.endNode( T) newField(pos parse.Pos, ident string) *parse.FieldNode( T) newIf(pos parse.Pos, line int, pipe *parse.PipeNode, list, elseList *parse.ListNode) *parse.IfNode( T) newList(pos parse.Pos) *parse.ListNode( T) newNil(pos parse.Pos) *parse.NilNode( T) newNumber(pos parse.Pos, text string, typ parse.itemType) (*parse.NumberNode, error)( T) newPipeline(pos parse.Pos, line int, vars []*parse.VariableNode) *parse.PipeNode( T) newRange(pos parse.Pos, line int, pipe *parse.PipeNode, list, elseList *parse.ListNode) *parse.RangeNode( T) newString(pos parse.Pos, orig, text string) *parse.StringNode( T) newTemplate(pos parse.Pos, line int, name string, pipe *parse.PipeNode) *parse.TemplateNode( T) newText(pos parse.Pos, text string) *parse.TextNode( T) newVariable(pos parse.Pos, ident string) *parse.VariableNode( T) newWith(pos parse.Pos, line int, pipe *parse.PipeNode, list, elseList *parse.ListNode) *parse.WithNode
next returns the next token.
nextNonSpace returns the next non-space token.
operand:
term .Field*
An operand is a space-separated component of a command,
a term possibly followed by field accesses.
A nil return means the next item is not an operand.
parse is the top-level parser for a template, essentially the same
as itemList except it also parses {{define}} actions.
It runs to EOF.
( T) parseControl(allowElseIf bool, context string) (pos parse.Pos, line int, pipe *parse.PipeNode, list, elseList *parse.ListNode)
parseDefinition parses a {{define}} ... {{end}} template definition and
installs the definition in t.treeSet. The "define" keyword has already
been scanned.
( T) parseTemplateName(token parse.item, context string) (name string)
peek returns but does not consume the next token.
peekNonSpace returns but does not consume the next non-space token.
Pipeline:
declarations? command ('|' command)*
popVars trims the variable list to the specified length
Range:
{{range pipeline}} itemList {{end}}
{{range pipeline}} itemList {{else}} itemList {{end}}
Range keyword is past.
recover is the handler that turns panics into returns from the top level of Parse.
(*T) setOption(opt string)
startParse initializes the parser, using the lexer.
stopParse terminates parsing.
Template:
{{template stringValue pipeline}}
Template keyword is past. The name must be something that can evaluate
to a string.
term:
literal (number, string, nil, boolean)
function (identifier)
.
.Field
$
'(' pipeline ')'
A term is a simple "expression".
A nil return means the next item is not a term.
textOrAction:
text | comment | action
unexpected complains about the token and terminates processing.
useVar returns a node for a variable reference. It errors if the
variable is not defined.
With:
{{with pipeline}} itemList {{end}}
{{with pipeline}} itemList {{else}} itemList {{end}}
If keyword is past.
func Must(t *Template, err error) *Template
func New(name string) *Template
func ParseFiles(filenames ...string) (*Template, error)
func ParseFS(fsys fs.FS, patterns ...string) (*Template, error)
func ParseGlob(pattern string) (*Template, error)
func (*Template).AddParseTree(name string, tree *parse.Tree) (*Template, error)
func (*Template).Clone() (*Template, error)
func (*Template).Delims(left, right string) *Template
func (*Template).Funcs(funcMap FuncMap) *Template
func (*Template).Lookup(name string) *Template
func (*Template).New(name string) *Template
func (*Template).Option(opt ...string) *Template
func (*Template).Parse(text string) (*Template, error)
func (*Template).ParseFiles(filenames ...string) (*Template, error)
func (*Template).ParseFS(fsys fs.FS, patterns ...string) (*Template, error)
func (*Template).ParseGlob(pattern string) (*Template, error)
func (*Template).Templates() []*Template
func parseFiles(t *Template, readFile func(string) (string, []byte, error), filenames ...string) (*Template, error)
func parseFS(t *Template, fsys fs.FS, patterns []string) (*Template, error)
func parseGlob(t *Template, pattern string) (*Template, error)
func (*Template).copy(c *common) *Template
func Must(t *Template, err error) *Template
func findFunction(name string, tmpl *Template) (reflect.Value, bool)
func parseFiles(t *Template, readFile func(string) (string, []byte, error), filenames ...string) (*Template, error)
func parseFS(t *Template, fsys fs.FS, patterns []string) (*Template, error)
func parseGlob(t *Template, pattern string) (*Template, error)
func (*Template).associate(new *Template, tree *parse.Tree) bool
func github.com/manifoldco/promptui.render(tpl *Template, data interface{}) []byte
common holds the information shared by related templates.
execFuncsmap[string]reflect.Value
We use two maps, one for parsing and one for execution.
This separation makes the API cleaner since it doesn't
expose reflection to the client.
// protects parseFuncs and execFuncs
optionoptionparseFuncsFuncMap
// Map from name to defined templates.
func (*Template).copy(c *common) *Template
state represents the state of an execution. It's not part of the
template so that multiple executions of the same template
can execute in parallel.
// the height of the stack of executing templates.
// current node, for errors
tmpl*Template
// push-down stack of variable values.
wrio.Writer
at marks the state to be on node n, for error reporting.
errorf records an ExecError and terminates processing.
(*T) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value(*T) evalBool(typ reflect.Type, n parse.Node) reflect.Value
evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
as the function itself.
(*T) evalChainNode(dot reflect.Value, chain *parse.ChainNode, args []parse.Node, final reflect.Value) reflect.Value(*T) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value(*T) evalComplex(typ reflect.Type, n parse.Node) reflect.Value(*T) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value
evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
The 'final' argument represents the return value from the preceding
value of the pipeline, if any.
evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
dot is the environment in which to evaluate arguments, while
receiver is the value being walked along the chain.
(*T) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value(*T) evalFloat(typ reflect.Type, n parse.Node) reflect.Value(*T) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value(*T) evalInteger(typ reflect.Type, n parse.Node) reflect.Value
evalPipeline returns the value acquired by evaluating a pipeline. If the
pipeline has a variable declaration, the variable will be pushed on the
stack. Callers should therefore pop the stack after they are finished
executing commands depending on the pipeline value.
(*T) evalString(typ reflect.Type, n parse.Node) reflect.Value(*T) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value(*T) evalVariableNode(dot reflect.Value, variable *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value
idealConstant is called to return the value of a number in a context where
we don't know the type. In that case, the syntax of the number tells us
its type, and we use Go rules to resolve. Note there is no such thing as
a uint ideal constant in this situation - the value must be of int type.
mark returns the length of the variable stack.
(*T) notAFunction(args []parse.Node, final reflect.Value)
pop pops the variable stack up to the mark.
printValue writes the textual representation of the value to the output of
the template.
push pushes a new variable on the stack.
setTopVar overwrites the top-nth variable on the stack. Used by range iterations.
setVar overwrites the last declared variable with the given name.
Used by variable assignments.
validateType guarantees that the value is valid and assignable to the type.
varValue returns the value of the named variable.
Walk functions step through the major pieces of the template structure,
generating output as they go.
walkIfOrWith walks an 'if' or 'with' node. The two control structures
are identical in behavior except that 'with' sets dot.
(*T) walkRange(dot reflect.Value, r *parse.RangeNode)(*T) walkTemplate(dot reflect.Value, t *parse.TemplateNode)(*T) writeError(err error)
writeError is the wrapper type used internally when Execute has an
error writing to its output. We strip the wrapper in errRecover.
Note that this is not an implementation of error, so it cannot escape
from the package as an error value.
Errerror
Package-Level Functions (total 57, in which 13 are exported)
HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.
HTMLEscaper returns the escaped HTML equivalent of the textual
representation of its arguments.
HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.
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.
JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.
JSEscaper returns the escaped JavaScript equivalent of the textual
representation of its arguments.
JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.
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"))
New allocates a new, undefined template with the given name.
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.
ParseFS is like ParseFiles or ParseGlob but reads from the file system fsys
instead of the host operating system's file system.
It accepts a list of glob patterns.
(Note that most file names serve as glob patterns matching only themselves.)
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.
URLQueryEscaper returns the escaped value of the textual representation of
its arguments in a form suitable for embedding in a URL query.
addFuncs adds to values the functions in funcs. It does no checking of the input -
call addValueFuncs first.
addValueFuncs adds to values the functions in funcs, converting them to reflect.Values.
and computes the Boolean AND of its arguments, returning
the first false argument it encounters, or the last argument.
builtinFuncsOnce lazily computes & caches the builtinFuncs map.
TODO: revert this back to a global map once golang.org/issue/2559 is fixed.
builtins returns the FuncMap.
It is not a global variable so the linker can dead code eliminate
more when this isn't called. See golang.org/issue/36021.
TODO: revert this back to a global map once golang.org/issue/2559 is fixed.
call returns the result of evaluating the first argument as a function.
The function must return 1 result, or 2 results, the second of which is an error.
canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero.
createValueFuncs turns a FuncMap into a map[string]reflect.Value
doublePercent returns the string with %'s replaced by %%, if necessary,
so it can be used safely inside a Printf format string.
eq evaluates the comparison a == b || a == c || ...
errRecover is the handler that turns panics into returns from the top
level of Parse.
evalArgs formats the list of arguments into a string. It is therefore equivalent to
fmt.Sprint(args...)
except that each argument is indirected (if a pointer), as required,
using the same rules as the default string evaluation during template
execution.
findFunction looks for a function in the template, and global map.
ge evaluates the comparison a >= b.
goodFunc reports whether the function or method has the right result signature.
goodName reports whether the function name is a valid identifier.
gt evaluates the comparison a > b.
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.
indexArg checks if a reflect.Value can be used as an index, and converts it to int if possible.
indirect returns the item at the end of indirection, and a bool to indicate
if it's nil. If the returned bool is true, the returned value's kind will be
either a pointer or interface.
indirectInterface returns the concrete value in an interface value,
or else the zero reflect.Value.
That is, if v represents the interface value x, the result is the same as reflect.ValueOf(x):
the fact that x was an interface value is forgotten.
safeCall runs fun.Call(args), and returns the resulting value and error, if
any. If the call panics, the panic value is returned as an error.
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.
maxExecDepth specifies the maximum stack depth of templates within
templates. This limit is only practically reached by accidentally
recursive template invocations. This limit allows us to return
an error instead of triggering a stack overflow.
The pages are generated with Goldsv0.3.2. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.