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