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