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