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