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

View as plain text