Source file src/text/template/doc.go

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  /*
     6  Package template implements data-driven templates for generating textual output.
     7  
     8  To generate HTML output, see [html/template], which has the same interface
     9  as this package but automatically secures HTML output against certain attacks.
    10  
    11  Templates are executed by applying them to a data structure. Annotations in the
    12  template refer to elements of the data structure (typically a field of a struct
    13  or a key in a map) to control execution and derive values to be displayed.
    14  Execution of the template walks the structure and sets the cursor, represented
    15  by a period '.' and called "dot", to the value at the current location in the
    16  structure as execution proceeds.
    17  
    18  The security model used by this package assumes that template authors are
    19  trusted. The package does not auto-escape output, so injecting code into
    20  a template can lead to arbitrary code execution if the template is executed
    21  by an untrusted source.
    22  
    23  The input text for a template is UTF-8-encoded text in any format.
    24  "Actions"--data evaluations or control structures--are delimited by
    25  "{{" and "}}"; all text outside actions is copied to the output unchanged.
    26  
    27  Once parsed, a template may be executed safely in parallel, although if parallel
    28  executions share a Writer the output may be interleaved.
    29  
    30  Here is a trivial example that prints "17 items are made of wool".
    31  
    32  	type Inventory struct {
    33  		Material string
    34  		Count    uint
    35  	}
    36  	sweaters := Inventory{"wool", 17}
    37  	tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
    38  	if err != nil { panic(err) }
    39  	err = tmpl.Execute(os.Stdout, sweaters)
    40  	if err != nil { panic(err) }
    41  
    42  More intricate examples appear below.
    43  
    44  Text and spaces
    45  
    46  By default, all text between actions is copied verbatim when the template is
    47  executed. For example, the string " items are made of " in the example above
    48  appears on standard output when the program is run.
    49  
    50  However, to aid in formatting template source code, if an action's left
    51  delimiter (by default "{{") is followed immediately by a minus sign and white
    52  space, all trailing white space is trimmed from the immediately preceding text.
    53  Similarly, if the right delimiter ("}}") is preceded by white space and a minus
    54  sign, all leading white space is trimmed from the immediately following text.
    55  In these trim markers, the white space must be present:
    56  "{{- 3}}" is like "{{3}}" but trims the immediately preceding text, while
    57  "{{-3}}" parses as an action containing the number -3.
    58  
    59  For instance, when executing the template whose source is
    60  
    61  	"{{23 -}} < {{- 45}}"
    62  
    63  the generated output would be
    64  
    65  	"23<45"
    66  
    67  For this trimming, the definition of white space characters is the same as in Go:
    68  space, horizontal tab, carriage return, and newline.
    69  
    70  Actions
    71  
    72  Here is the list of actions. "Arguments" and "pipelines" are evaluations of
    73  data, defined in detail in the corresponding sections that follow.
    74  
    75  */
    76  //	{{/* a comment */}}
    77  //	{{- /* a comment with white space trimmed from preceding and following text */ -}}
    78  //		A comment; discarded. May contain newlines.
    79  //		Comments do not nest and must start and end at the
    80  //		delimiters, as shown here.
    81  /*
    82  
    83  	{{pipeline}}
    84  		The default textual representation (the same as would be
    85  		printed by fmt.Print) of the value of the pipeline is copied
    86  		to the output.
    87  
    88  	{{if pipeline}} T1 {{end}}
    89  		If the value of the pipeline is empty, no output is generated;
    90  		otherwise, T1 is executed. The empty values are false, 0, any
    91  		nil pointer or interface value, and any array, slice, map, or
    92  		string of length zero.
    93  		Dot is unaffected.
    94  
    95  	{{if pipeline}} T1 {{else}} T0 {{end}}
    96  		If the value of the pipeline is empty, T0 is executed;
    97  		otherwise, T1 is executed. Dot is unaffected.
    98  
    99  	{{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
   100  		To simplify the appearance of if-else chains, the else action
   101  		of an if may include another if directly; the effect is exactly
   102  		the same as writing
   103  			{{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}}
   104  
   105  	{{range pipeline}} T1 {{end}}
   106  		The value of the pipeline must be an array, slice, map, iter.Seq,
   107  		iter.Seq2, integer or channel.
   108  		If the value of the pipeline has length zero, nothing is output;
   109  		otherwise, dot is set to the successive elements of the array,
   110  		slice, or map and T1 is executed. If the value is a map and the
   111  		keys are of basic type with a defined order, the elements will be
   112  		visited in sorted key order.
   113  
   114  	{{range pipeline}} T1 {{else}} T0 {{end}}
   115  		The value of the pipeline must be an array, slice, map, iter.Seq,
   116  		iter.Seq2, integer or channel.
   117  		If the value of the pipeline has length zero, dot is unaffected and
   118  		T0 is executed; otherwise, dot is set to the successive elements
   119  		of the array, slice, or map and T1 is executed.
   120  
   121  	{{break}}
   122  		The innermost {{range pipeline}} loop is ended early, stopping the
   123  		current iteration and bypassing all remaining iterations.
   124  
   125  	{{continue}}
   126  		The current iteration of the innermost {{range pipeline}} loop is
   127  		stopped, and the loop starts the next iteration.
   128  
   129  	{{template "name"}}
   130  		The template with the specified name is executed with nil data.
   131  
   132  	{{template "name" pipeline}}
   133  		The template with the specified name is executed with dot set
   134  		to the value of the pipeline.
   135  
   136  	{{block "name" pipeline}} T1 {{end}}
   137  		A block is shorthand for defining a template
   138  			{{define "name"}} T1 {{end}}
   139  		and then executing it in place
   140  			{{template "name" pipeline}}
   141  		The typical use is to define a set of root templates that are
   142  		then customized by redefining the block templates within.
   143  
   144  	{{with pipeline}} T1 {{end}}
   145  		If the value of the pipeline is empty, no output is generated;
   146  		otherwise, dot is set to the value of the pipeline and T1 is
   147  		executed.
   148  
   149  	{{with pipeline}} T1 {{else}} T0 {{end}}
   150  		If the value of the pipeline is empty, dot is unaffected and T0
   151  		is executed; otherwise, dot is set to the value of the pipeline
   152  		and T1 is executed.
   153  
   154  	{{with pipeline}} T1 {{else with pipeline}} T0 {{end}}
   155  		To simplify the appearance of with-else chains, the else action
   156  		of a with may include another with directly; the effect is exactly
   157  		the same as writing
   158  			{{with pipeline}} T1 {{else}}{{with pipeline}} T0 {{end}}{{end}}
   159  
   160  
   161  Arguments
   162  
   163  An argument is a simple value, denoted by one of the following.
   164  
   165  	- A boolean, string, character, integer, floating-point, imaginary
   166  	  or complex constant in Go syntax. These behave like Go's untyped
   167  	  constants. Note that, as in Go, whether a large integer constant
   168  	  overflows when assigned or passed to a function can depend on whether
   169  	  the host machine's ints are 32 or 64 bits.
   170  	- The keyword nil, representing an untyped Go nil.
   171  	- The character '.' (period):
   172  
   173  		.
   174  
   175  	  The result is the value of dot.
   176  	- A variable name, which is a (possibly empty) alphanumeric string
   177  	  preceded by a dollar sign, such as
   178  
   179  		$piOver2
   180  
   181  	  or
   182  
   183  		$
   184  
   185  	  The result is the value of the variable.
   186  	  Variables are described below.
   187  	- The name of a field of the data, which must be a struct, preceded
   188  	  by a period, such as
   189  
   190  		.Field
   191  
   192  	  The result is the value of the field. Field invocations may be
   193  	  chained:
   194  
   195  	    .Field1.Field2
   196  
   197  	  Fields can also be evaluated on variables, including chaining:
   198  
   199  	    $x.Field1.Field2
   200  	- The name of a key of the data, which must be a map, preceded
   201  	  by a period, such as
   202  
   203  		.Key
   204  
   205  	  The result is the map element value indexed by the key.
   206  	  Key invocations may be chained and combined with fields to any
   207  	  depth:
   208  
   209  	    .Field1.Key1.Field2.Key2
   210  
   211  	  Although the key must be an alphanumeric identifier, unlike with
   212  	  field names they do not need to start with an upper case letter.
   213  	  Keys can also be evaluated on variables, including chaining:
   214  
   215  	    $x.key1.key2
   216  	- The name of a niladic method of the data, preceded by a period,
   217  	  such as
   218  
   219  		.Method
   220  
   221  	  The result is the value of invoking the method with dot as the
   222  	  receiver, dot.Method(). Such a method must have one return value (of
   223  	  any type) or two return values, the second of which is an error.
   224  	  If it has two and the returned error is non-nil, execution terminates
   225  	  and an error is returned to the caller as the value of Execute.
   226  	  Method invocations may be chained and combined with fields and keys
   227  	  to any depth:
   228  
   229  	    .Field1.Key1.Method1.Field2.Key2.Method2
   230  
   231  	  Methods can also be evaluated on variables, including chaining:
   232  
   233  	    $x.Method1.Field
   234  	- The name of a niladic function, such as
   235  
   236  		fun
   237  
   238  	  The result is the value of invoking the function, fun(). The return
   239  	  types and values behave as in methods. Functions and function
   240  	  names are described below.
   241  	- A parenthesized instance of one the above, for grouping. The result
   242  	  may be accessed by a field or map key invocation.
   243  
   244  		print (.F1 arg1) (.F2 arg2)
   245  		(.StructValuedMethod "arg").Field
   246  
   247  Arguments may evaluate to any type; if they are pointers the implementation
   248  automatically indirects to the base type when required.
   249  If an evaluation yields a function value, such as a function-valued
   250  field of a struct, the function is not invoked automatically, but it
   251  can be used as a truth value for an if action and the like. To invoke
   252  it, use the call function, defined below.
   253  
   254  Pipelines
   255  
   256  A pipeline is a possibly chained sequence of "commands". A command is a simple
   257  value (argument) or a function or method call, possibly with multiple arguments:
   258  
   259  	Argument
   260  		The result is the value of evaluating the argument.
   261  	.Method [Argument...]
   262  		The method can be alone or the last element of a chain but,
   263  		unlike methods in the middle of a chain, it can take arguments.
   264  		The result is the value of calling the method with the
   265  		arguments:
   266  			dot.Method(Argument1, etc.)
   267  	functionName [Argument...]
   268  		The result is the value of calling the function associated
   269  		with the name:
   270  			function(Argument1, etc.)
   271  		Functions and function names are described below.
   272  
   273  A pipeline may be "chained" by separating a sequence of commands with pipeline
   274  characters '|'. In a chained pipeline, the result of each command is
   275  passed as the last argument of the following command. The output of the final
   276  command in the pipeline is the value of the pipeline.
   277  
   278  The output of a command will be either one value or two values, the second of
   279  which has type error. If that second value is present and evaluates to
   280  non-nil, execution terminates and the error is returned to the caller of
   281  Execute.
   282  
   283  Variables
   284  
   285  A pipeline inside an action may initialize a variable to capture the result.
   286  The initialization has syntax
   287  
   288  	$variable := pipeline
   289  
   290  where $variable is the name of the variable. An action that declares a
   291  variable produces no output.
   292  
   293  Variables previously declared can also be assigned, using the syntax
   294  
   295  	$variable = pipeline
   296  
   297  If a "range" action initializes a variable, the variable is set to the
   298  successive elements of the iteration. Also, a "range" may declare two
   299  variables, separated by a comma:
   300  
   301  	range $index, $element := pipeline
   302  
   303  in which case $index and $element are set to the successive values of the
   304  array/slice index or map key and element, respectively. Note that if there is
   305  only one variable, it is assigned the element; this is opposite to the
   306  convention in Go range clauses.
   307  
   308  A variable's scope extends to the "end" action of the control structure ("if",
   309  "with", or "range") in which it is declared, or to the end of the template if
   310  there is no such control structure. A template invocation does not inherit
   311  variables from the point of its invocation.
   312  
   313  When execution begins, $ is set to the data argument passed to Execute, that is,
   314  to the starting value of dot.
   315  
   316  Examples
   317  
   318  Here are some example one-line templates demonstrating pipelines and variables.
   319  All produce the quoted word "output":
   320  
   321  	{{"\"output\""}}
   322  		A string constant.
   323  	{{`"output"`}}
   324  		A raw string constant.
   325  	{{printf "%q" "output"}}
   326  		A function call.
   327  	{{"output" | printf "%q"}}
   328  		A function call whose final argument comes from the previous
   329  		command.
   330  	{{printf "%q" (print "out" "put")}}
   331  		A parenthesized argument.
   332  	{{"put" | printf "%s%s" "out" | printf "%q"}}
   333  		A more elaborate call.
   334  	{{"output" | printf "%s" | printf "%q"}}
   335  		A longer chain.
   336  	{{with "output"}}{{printf "%q" .}}{{end}}
   337  		A with action using dot.
   338  	{{with $x := "output" | printf "%q"}}{{$x}}{{end}}
   339  		A with action that creates and uses a variable.
   340  	{{with $x := "output"}}{{printf "%q" $x}}{{end}}
   341  		A with action that uses the variable in another action.
   342  	{{with $x := "output"}}{{$x | printf "%q"}}{{end}}
   343  		The same, but pipelined.
   344  
   345  Functions
   346  
   347  During execution functions are found in two function maps: first in the
   348  template, then in the global function map. By default, no functions are defined
   349  in the template but the Funcs method can be used to add them.
   350  
   351  Predefined global functions are named as follows.
   352  
   353  	and
   354  		Returns the boolean AND of its arguments by returning the
   355  		first empty argument or the last argument. That is,
   356  		"and x y" behaves as "if x then y else x."
   357  		Evaluation proceeds through the arguments left to right
   358  		and returns when the result is determined.
   359  	call
   360  		Returns the result of calling the first argument, which
   361  		must be a function, with the remaining arguments as parameters.
   362  		Thus "call .X.Y 1 2" is, in Go notation, dot.X.Y(1, 2) where
   363  		Y is a func-valued field, map entry, or the like.
   364  		The first argument must be the result of an evaluation
   365  		that yields a value of function type (as distinct from
   366  		a predefined function such as print). The function must
   367  		return either one or two result values, the second of which
   368  		is of type error. If the arguments don't match the function
   369  		or the returned error value is non-nil, execution stops.
   370  	html
   371  		Returns the escaped HTML equivalent of the textual
   372  		representation of its arguments. This function is unavailable
   373  		in html/template, with a few exceptions.
   374  	index
   375  		Returns the result of indexing its first argument by the
   376  		following arguments. Thus "index x 1 2 3" is, in Go syntax,
   377  		x[1][2][3]. Each indexed item must be a map, slice, or array.
   378  	slice
   379  		slice returns the result of slicing its first argument by the
   380  		remaining arguments. Thus "slice x 1 2" is, in Go syntax, x[1:2],
   381  		while "slice x" is x[:], "slice x 1" is x[1:], and "slice x 1 2 3"
   382  		is x[1:2:3]. The first argument must be a string, slice, or array.
   383  	js
   384  		Returns the escaped JavaScript equivalent of the textual
   385  		representation of its arguments.
   386  	len
   387  		Returns the integer length of its argument.
   388  	not
   389  		Returns the boolean negation of its single argument.
   390  	or
   391  		Returns the boolean OR of its arguments by returning the
   392  		first non-empty argument or the last argument, that is,
   393  		"or x y" behaves as "if x then x else y".
   394  		Evaluation proceeds through the arguments left to right
   395  		and returns when the result is determined.
   396  	print
   397  		An alias for fmt.Sprint
   398  	printf
   399  		An alias for fmt.Sprintf
   400  	println
   401  		An alias for fmt.Sprintln
   402  	urlquery
   403  		Returns the escaped value of the textual representation of
   404  		its arguments in a form suitable for embedding in a URL query.
   405  		This function is unavailable in html/template, with a few
   406  		exceptions.
   407  
   408  The boolean functions take any zero value to be false and a non-zero
   409  value to be true.
   410  
   411  There is also a set of binary comparison operators defined as
   412  functions:
   413  
   414  	eq
   415  		Returns the boolean truth of arg1 == arg2
   416  	ne
   417  		Returns the boolean truth of arg1 != arg2
   418  	lt
   419  		Returns the boolean truth of arg1 < arg2
   420  	le
   421  		Returns the boolean truth of arg1 <= arg2
   422  	gt
   423  		Returns the boolean truth of arg1 > arg2
   424  	ge
   425  		Returns the boolean truth of arg1 >= arg2
   426  
   427  For simpler multi-way equality tests, eq (only) accepts two or more
   428  arguments and compares the second and subsequent to the first,
   429  returning in effect
   430  
   431  	arg1==arg2 || arg1==arg3 || arg1==arg4 ...
   432  
   433  (Unlike with || in Go, however, eq is a function call and all the
   434  arguments will be evaluated.)
   435  
   436  The comparison functions work on any values whose type Go defines as
   437  comparable. For basic types such as integers, the rules are relaxed:
   438  size and exact type are ignored, so any integer value, signed or unsigned,
   439  may be compared with any other integer value. (The arithmetic value is compared,
   440  not the bit pattern, so all negative integers are less than all unsigned integers.)
   441  However, as usual, one may not compare an int with a float32 and so on.
   442  
   443  Associated templates
   444  
   445  Each template is named by a string specified when it is created. Also, each
   446  template is associated with zero or more other templates that it may invoke by
   447  name; such associations are transitive and form a name space of templates.
   448  
   449  A template may use a template invocation to instantiate another associated
   450  template; see the explanation of the "template" action above. The name must be
   451  that of a template associated with the template that contains the invocation.
   452  
   453  Nested template definitions
   454  
   455  When parsing a template, another template may be defined and associated with the
   456  template being parsed. Template definitions must appear at the top level of the
   457  template, much like global variables in a Go program.
   458  
   459  The syntax of such definitions is to surround each template declaration with a
   460  "define" and "end" action.
   461  
   462  The define action names the template being created by providing a string
   463  constant. Here is a simple example:
   464  
   465  	{{define "T1"}}ONE{{end}}
   466  	{{define "T2"}}TWO{{end}}
   467  	{{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}}
   468  	{{template "T3"}}
   469  
   470  This defines two templates, T1 and T2, and a third T3 that invokes the other two
   471  when it is executed. Finally it invokes T3. If executed this template will
   472  produce the text
   473  
   474  	ONE TWO
   475  
   476  By construction, a template may reside in only one association. If it's
   477  necessary to have a template addressable from multiple associations, the
   478  template definition must be parsed multiple times to create distinct *Template
   479  values, or must be copied with [Template.Clone] or [Template.AddParseTree].
   480  
   481  Parse may be called multiple times to assemble the various associated templates;
   482  see [ParseFiles], [ParseGlob], [Template.ParseFiles] and [Template.ParseGlob]
   483  for simple ways to parse related templates stored in files.
   484  
   485  A template may be executed directly or through [Template.ExecuteTemplate], which executes
   486  an associated template identified by name. To invoke our example above, we
   487  might write,
   488  
   489  	err := tmpl.Execute(os.Stdout, "no data needed")
   490  	if err != nil {
   491  		log.Fatalf("execution failed: %s", err)
   492  	}
   493  
   494  or to invoke a particular template explicitly by name,
   495  
   496  	err := tmpl.ExecuteTemplate(os.Stdout, "T2", "no data needed")
   497  	if err != nil {
   498  		log.Fatalf("execution failed: %s", err)
   499  	}
   500  
   501  */
   502  package template
   503  

View as plain text