github.com/flyinox/gosm@v0.0.0-20171117061539-16768cb62077/src/text/template/doc.go (about)

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