· 6 years ago · Jan 02, 2020, 04:22 PM
1<!DOCTYPE html>
2<html lang="en">
3<meta charset="utf-8">
4<meta name="description" content="Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.">
5<meta name="viewport" content="width=device-width, initial-scale=1">
6<meta name="theme-color" content="#00ADD8">
7
8 <title>template - The Go Programming Language</title>
9
10<link href="https://fonts.googleapis.com/css?family=Work+Sans:600|Roboto:400,700" rel="stylesheet">
11<link href="https://fonts.googleapis.com/css?family=Product+Sans&text=Supported%20by%20Google&display=swap" rel="stylesheet">
12<link type="text/css" rel="stylesheet" href="/lib/godoc/style.css">
13
14<link rel="search" type="application/opensearchdescription+xml" title="godoc" href="/opensearch.xml" />
15
16<script>window.initFuncs = [];</script>
17
18<script>
19var _gaq = _gaq || [];
20_gaq.push(["_setAccount", "UA-11222381-2"]);
21window.trackPageview = function() {
22 _gaq.push(["_trackPageview", location.pathname+location.hash]);
23};
24window.trackPageview();
25window.trackEvent = function(category, action, opt_label, opt_value, opt_noninteraction) {
26 _gaq.push(["_trackEvent", category, action, opt_label, opt_value, opt_noninteraction]);
27};
28</script>
29
30<script src="/lib/godoc/jquery.js" defer></script>
31
32
33<script src="/lib/godoc/playground.js" defer></script>
34
35<script>var goVersion = "go1.13.5";</script>
36<script src="/lib/godoc/godocs.js" defer></script>
37
38<body class="Site">
39<header class="Header js-header">
40 <nav class="Header-nav Header-nav--wide">
41 <a href="/"><img class="Header-logo" src="/lib/godoc/images/go-logo-blue.svg" alt="Go"></a>
42 <button class="Header-menuButton js-headerMenuButton" aria-label="Main menu" aria-expanded="false">
43 <div class="Header-menuButtonInner">
44 </button>
45 <ul class="Header-menu">
46 <li class="Header-menuItem"><a href="/doc/">Documents</a></li>
47 <li class="Header-menuItem"><a href="/pkg/">Packages</a></li>
48 <li class="Header-menuItem"><a href="/project/">The Project</a></li>
49 <li class="Header-menuItem"><a href="/help/">Help</a></li>
50
51 <li class="Header-menuItem"><a href="/blog/">Blog</a></li>
52
53 <li class="Header-menuItem"><a href="https://play.golang.org/">Play</a></li>
54
55
56 <li class="Header-menuItem Header-menuItem--search">
57 <form class="HeaderSearch" role="search" action="/search">
58 <input class="HeaderSearch-input"
59 type="search"
60 name="q"
61 placeholder="Search"
62 aria-label="Search"
63 autocapitalize="off"
64 autocomplete="off"
65 autocorrect="off"
66 spellcheck="false"
67 required>
68 <button class="HeaderSearch-submit">
69 <!-- magnifying glass: --><svg class="HeaderSearch-icon" width="24" height="24" viewBox="0 0 24 24"><title>Search</title><path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/><path d="M0 0h24v24H0z" fill="none"/></svg>
70 </button>
71 </form>
72 </li>
73 </ul>
74 </nav>
75</header>
76
77<main id="page" class="Site-content wide">
78<div class="container">
79
80
81 <h1>
82 Package template
83 <span class="text-muted"></span>
84 </h1>
85
86
87
88
89
90
91
92<div id="nav"></div>
93
94
95<!--
96 Copyright 2009 The Go Authors. All rights reserved.
97 Use of this source code is governed by a BSD-style
98 license that can be found in the LICENSE file.
99-->
100<!--
101 Note: Static (i.e., not template-generated) href and id
102 attributes start with "pkg-" to make it impossible for
103 them to conflict with generated attributes (some of which
104 correspond to Go identifiers).
105-->
106
107
108
109 <div id="short-nav">
110 <dl>
111 <dd><code>import "text/template"</code></dd>
112 </dl>
113 <dl>
114 <dd><a href="#pkg-overview" class="overviewLink">Overview</a></dd>
115 <dd><a href="#pkg-index" class="indexLink">Index</a></dd>
116
117 <dd><a href="#pkg-examples" class="examplesLink">Examples</a></dd>
118
119
120 <dd><a href="#pkg-subdirectories">Subdirectories</a></dd>
121
122 </dl>
123 </div>
124 <!-- The package's Name is printed as title by the top-level template -->
125 <div id="pkg-overview" class="toggleVisible">
126 <div class="collapsed">
127 <h2 class="toggleButton" title="Click to show Overview section">Overview ▹</h2>
128 </div>
129 <div class="expanded">
130 <h2 class="toggleButton" title="Click to hide Overview section">Overview ▾</h2>
131 <p>
132Package template implements data-driven templates for generating textual output.
133</p>
134<p>
135To generate HTML output, see package html/template, which has the same interface
136as this package but automatically secures HTML output against certain attacks.
137</p>
138<p>
139Templates are executed by applying them to a data structure. Annotations in the
140template refer to elements of the data structure (typically a field of a struct
141or a key in a map) to control execution and derive values to be displayed.
142Execution of the template walks the structure and sets the cursor, represented
143by a period '.' and called "dot", to the value at the current location in the
144structure as execution proceeds.
145</p>
146<p>
147The input text for a template is UTF-8-encoded text in any format.
148"Actions"--data evaluations or control structures--are delimited by
149"{{" and "}}"; all text outside actions is copied to the output unchanged.
150Except for raw strings, actions may not span newlines, although comments can.
151</p>
152<p>
153Once parsed, a template may be executed safely in parallel, although if parallel
154executions share a Writer the output may be interleaved.
155</p>
156<p>
157Here is a trivial example that prints "17 items are made of wool".
158</p>
159<pre>type Inventory struct {
160 Material string
161 Count uint
162}
163sweaters := Inventory{"wool", 17}
164tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
165if err != nil { panic(err) }
166err = tmpl.Execute(os.Stdout, sweaters)
167if err != nil { panic(err) }
168</pre>
169<p>
170More intricate examples appear below.
171</p>
172<h3 id="hdr-Text_and_spaces">Text and spaces</h3>
173<p>
174By default, all text between actions is copied verbatim when the template is
175executed. For example, the string " items are made of " in the example above appears
176on standard output when the program is run.
177</p>
178<p>
179However, to aid in formatting template source code, if an action's left delimiter
180(by default "{{") is followed immediately by a minus sign and ASCII space character
181("{{- "), all trailing white space is trimmed from the immediately preceding text.
182Similarly, if the right delimiter ("}}") is preceded by a space and minus sign
183(" -}}"), all leading white space is trimmed from the immediately following text.
184In these trim markers, the ASCII space must be present; "{{-3}}" parses as an
185action containing the number -3.
186</p>
187<p>
188For instance, when executing the template whose source is
189</p>
190<pre>"{{23 -}} < {{- 45}}"
191</pre>
192<p>
193the generated output would be
194</p>
195<pre>"23<45"
196</pre>
197<p>
198For this trimming, the definition of white space characters is the same as in Go:
199space, horizontal tab, carriage return, and newline.
200</p>
201<h3 id="hdr-Actions">Actions</h3>
202<p>
203Here is the list of actions. "Arguments" and "pipelines" are evaluations of
204data, defined in detail in the corresponding sections that follow.
205</p>
206<pre>{{/* a comment */}}
207{{- /* a comment with white space trimmed from preceding and following text */ -}}
208 A comment; discarded. May contain newlines.
209 Comments do not nest and must start and end at the
210 delimiters, as shown here.
211
212{{pipeline}}
213 The default textual representation (the same as would be
214 printed by fmt.Print) of the value of the pipeline is copied
215 to the output.
216
217{{if pipeline}} T1 {{end}}
218 If the value of the pipeline is empty, no output is generated;
219 otherwise, T1 is executed. The empty values are false, 0, any
220 nil pointer or interface value, and any array, slice, map, or
221 string of length zero.
222 Dot is unaffected.
223
224{{if pipeline}} T1 {{else}} T0 {{end}}
225 If the value of the pipeline is empty, T0 is executed;
226 otherwise, T1 is executed. Dot is unaffected.
227
228{{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
229 To simplify the appearance of if-else chains, the else action
230 of an if may include another if directly; the effect is exactly
231 the same as writing
232 {{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}}
233
234{{range pipeline}} T1 {{end}}
235 The value of the pipeline must be an array, slice, map, or channel.
236 If the value of the pipeline has length zero, nothing is output;
237 otherwise, dot is set to the successive elements of the array,
238 slice, or map and T1 is executed. If the value is a map and the
239 keys are of basic type with a defined order ("comparable"), the
240 elements will be visited in sorted key order.
241
242{{range pipeline}} T1 {{else}} T0 {{end}}
243 The value of the pipeline must be an array, slice, map, or channel.
244 If the value of the pipeline has length zero, dot is unaffected and
245 T0 is executed; otherwise, dot is set to the successive elements
246 of the array, slice, or map and T1 is executed.
247
248{{template "name"}}
249 The template with the specified name is executed with nil data.
250
251{{template "name" pipeline}}
252 The template with the specified name is executed with dot set
253 to the value of the pipeline.
254
255{{block "name" pipeline}} T1 {{end}}
256 A block is shorthand for defining a template
257 {{define "name"}} T1 {{end}}
258 and then executing it in place
259 {{template "name" pipeline}}
260 The typical use is to define a set of root templates that are
261 then customized by redefining the block templates within.
262
263{{with pipeline}} T1 {{end}}
264 If the value of the pipeline is empty, no output is generated;
265 otherwise, dot is set to the value of the pipeline and T1 is
266 executed.
267
268{{with pipeline}} T1 {{else}} T0 {{end}}
269 If the value of the pipeline is empty, dot is unaffected and T0
270 is executed; otherwise, dot is set to the value of the pipeline
271 and T1 is executed.
272</pre>
273<h3 id="hdr-Arguments">Arguments</h3>
274<p>
275An argument is a simple value, denoted by one of the following.
276</p>
277<pre>- A boolean, string, character, integer, floating-point, imaginary
278 or complex constant in Go syntax. These behave like Go's untyped
279 constants. Note that, as in Go, whether a large integer constant
280 overflows when assigned or passed to a function can depend on whether
281 the host machine's ints are 32 or 64 bits.
282- The keyword nil, representing an untyped Go nil.
283- The character '.' (period):
284 .
285 The result is the value of dot.
286- A variable name, which is a (possibly empty) alphanumeric string
287 preceded by a dollar sign, such as
288 $piOver2
289 or
290 $
291 The result is the value of the variable.
292 Variables are described below.
293- The name of a field of the data, which must be a struct, preceded
294 by a period, such as
295 .Field
296 The result is the value of the field. Field invocations may be
297 chained:
298 .Field1.Field2
299 Fields can also be evaluated on variables, including chaining:
300 $x.Field1.Field2
301- The name of a key of the data, which must be a map, preceded
302 by a period, such as
303 .Key
304 The result is the map element value indexed by the key.
305 Key invocations may be chained and combined with fields to any
306 depth:
307 .Field1.Key1.Field2.Key2
308 Although the key must be an alphanumeric identifier, unlike with
309 field names they do not need to start with an upper case letter.
310 Keys can also be evaluated on variables, including chaining:
311 $x.key1.key2
312- The name of a niladic method of the data, preceded by a period,
313 such as
314 .Method
315 The result is the value of invoking the method with dot as the
316 receiver, dot.Method(). Such a method must have one return value (of
317 any type) or two return values, the second of which is an error.
318 If it has two and the returned error is non-nil, execution terminates
319 and an error is returned to the caller as the value of Execute.
320 Method invocations may be chained and combined with fields and keys
321 to any depth:
322 .Field1.Key1.Method1.Field2.Key2.Method2
323 Methods can also be evaluated on variables, including chaining:
324 $x.Method1.Field
325- The name of a niladic function, such as
326 fun
327 The result is the value of invoking the function, fun(). The return
328 types and values behave as in methods. Functions and function
329 names are described below.
330- A parenthesized instance of one the above, for grouping. The result
331 may be accessed by a field or map key invocation.
332 print (.F1 arg1) (.F2 arg2)
333 (.StructValuedMethod "arg").Field
334</pre>
335<p>
336Arguments may evaluate to any type; if they are pointers the implementation
337automatically indirects to the base type when required.
338If an evaluation yields a function value, such as a function-valued
339field of a struct, the function is not invoked automatically, but it
340can be used as a truth value for an if action and the like. To invoke
341it, use the call function, defined below.
342</p>
343<h3 id="hdr-Pipelines">Pipelines</h3>
344<p>
345A pipeline is a possibly chained sequence of "commands". A command is a simple
346value (argument) or a function or method call, possibly with multiple arguments:
347</p>
348<pre>Argument
349 The result is the value of evaluating the argument.
350.Method [Argument...]
351 The method can be alone or the last element of a chain but,
352 unlike methods in the middle of a chain, it can take arguments.
353 The result is the value of calling the method with the
354 arguments:
355 dot.Method(Argument1, etc.)
356functionName [Argument...]
357 The result is the value of calling the function associated
358 with the name:
359 function(Argument1, etc.)
360 Functions and function names are described below.
361</pre>
362<p>
363A pipeline may be "chained" by separating a sequence of commands with pipeline
364characters '|'. In a chained pipeline, the result of each command is
365passed as the last argument of the following command. The output of the final
366command in the pipeline is the value of the pipeline.
367</p>
368<p>
369The output of a command will be either one value or two values, the second of
370which has type error. If that second value is present and evaluates to
371non-nil, execution terminates and the error is returned to the caller of
372Execute.
373</p>
374<h3 id="hdr-Variables">Variables</h3>
375<p>
376A pipeline inside an action may initialize a variable to capture the result.
377The initialization has syntax
378</p>
379<pre>$variable := pipeline
380</pre>
381<p>
382where $variable is the name of the variable. An action that declares a
383variable produces no output.
384</p>
385<p>
386Variables previously declared can also be assigned, using the syntax
387</p>
388<pre>$variable = pipeline
389</pre>
390<p>
391If a "range" action initializes a variable, the variable is set to the
392successive elements of the iteration. Also, a "range" may declare two
393variables, separated by a comma:
394</p>
395<pre>range $index, $element := pipeline
396</pre>
397<p>
398in which case $index and $element are set to the successive values of the
399array/slice index or map key and element, respectively. Note that if there is
400only one variable, it is assigned the element; this is opposite to the
401convention in Go range clauses.
402</p>
403<p>
404A variable's scope extends to the "end" action of the control structure ("if",
405"with", or "range") in which it is declared, or to the end of the template if
406there is no such control structure. A template invocation does not inherit
407variables from the point of its invocation.
408</p>
409<p>
410When execution begins, $ is set to the data argument passed to Execute, that is,
411to the starting value of dot.
412</p>
413<h3 id="hdr-Examples">Examples</h3>
414<p>
415Here are some example one-line templates demonstrating pipelines and variables.
416All produce the quoted word "output":
417</p>
418<pre>{{"\"output\""}}
419 A string constant.
420{{`"output"`}}
421 A raw string constant.
422{{printf "%q" "output"}}
423 A function call.
424{{"output" | printf "%q"}}
425 A function call whose final argument comes from the previous
426 command.
427{{printf "%q" (print "out" "put")}}
428 A parenthesized argument.
429{{"put" | printf "%s%s" "out" | printf "%q"}}
430 A more elaborate call.
431{{"output" | printf "%s" | printf "%q"}}
432 A longer chain.
433{{with "output"}}{{printf "%q" .}}{{end}}
434 A with action using dot.
435{{with $x := "output" | printf "%q"}}{{$x}}{{end}}
436 A with action that creates and uses a variable.
437{{with $x := "output"}}{{printf "%q" $x}}{{end}}
438 A with action that uses the variable in another action.
439{{with $x := "output"}}{{$x | printf "%q"}}{{end}}
440 The same, but pipelined.
441</pre>
442<h3 id="hdr-Functions">Functions</h3>
443<p>
444During execution functions are found in two function maps: first in the
445template, then in the global function map. By default, no functions are defined
446in the template but the Funcs method can be used to add them.
447</p>
448<p>
449Predefined global functions are named as follows.
450</p>
451<pre>and
452 Returns the boolean AND of its arguments by returning the
453 first empty argument or the last argument, that is,
454 "and x y" behaves as "if x then y else x". All the
455 arguments are evaluated.
456call
457 Returns the result of calling the first argument, which
458 must be a function, with the remaining arguments as parameters.
459 Thus "call .X.Y 1 2" is, in Go notation, dot.X.Y(1, 2) where
460 Y is a func-valued field, map entry, or the like.
461 The first argument must be the result of an evaluation
462 that yields a value of function type (as distinct from
463 a predefined function such as print). The function must
464 return either one or two result values, the second of which
465 is of type error. If the arguments don't match the function
466 or the returned error value is non-nil, execution stops.
467html
468 Returns the escaped HTML equivalent of the textual
469 representation of its arguments. This function is unavailable
470 in html/template, with a few exceptions.
471index
472 Returns the result of indexing its first argument by the
473 following arguments. Thus "index x 1 2 3" is, in Go syntax,
474 x[1][2][3]. Each indexed item must be a map, slice, or array.
475slice
476 slice returns the result of slicing its first argument by the
477 remaining arguments. Thus "slice x 1 2" is, in Go syntax, x[1:2],
478 while "slice x" is x[:], "slice x 1" is x[1:], and "slice x 1 2 3"
479 is x[1:2:3]. The first argument must be a string, slice, or array.
480js
481 Returns the escaped JavaScript equivalent of the textual
482 representation of its arguments.
483len
484 Returns the integer length of its argument.
485not
486 Returns the boolean negation of its single argument.
487or
488 Returns the boolean OR of its arguments by returning the
489 first non-empty argument or the last argument, that is,
490 "or x y" behaves as "if x then x else y". All the
491 arguments are evaluated.
492print
493 An alias for fmt.Sprint
494printf
495 An alias for fmt.Sprintf
496println
497 An alias for fmt.Sprintln
498urlquery
499 Returns the escaped value of the textual representation of
500 its arguments in a form suitable for embedding in a URL query.
501 This function is unavailable in html/template, with a few
502 exceptions.
503</pre>
504<p>
505The boolean functions take any zero value to be false and a non-zero
506value to be true.
507</p>
508<p>
509There is also a set of binary comparison operators defined as
510functions:
511</p>
512<pre>eq
513 Returns the boolean truth of arg1 == arg2
514ne
515 Returns the boolean truth of arg1 != arg2
516lt
517 Returns the boolean truth of arg1 < arg2
518le
519 Returns the boolean truth of arg1 <= arg2
520gt
521 Returns the boolean truth of arg1 > arg2
522ge
523 Returns the boolean truth of arg1 >= arg2
524</pre>
525<p>
526For simpler multi-way equality tests, eq (only) accepts two or more
527arguments and compares the second and subsequent to the first,
528returning in effect
529</p>
530<pre>arg1==arg2 || arg1==arg3 || arg1==arg4 ...
531</pre>
532<p>
533(Unlike with || in Go, however, eq is a function call and all the
534arguments will be evaluated.)
535</p>
536<p>
537The comparison functions work on basic types only (or named basic
538types, such as "type Celsius float32"). They implement the Go rules
539for comparison of values, except that size and exact type are
540ignored, so any integer value, signed or unsigned, may be compared
541with any other integer value. (The arithmetic value is compared,
542not the bit pattern, so all negative integers are less than all
543unsigned integers.) However, as usual, one may not compare an int
544with a float32 and so on.
545</p>
546<h3 id="hdr-Associated_templates">Associated templates</h3>
547<p>
548Each template is named by a string specified when it is created. Also, each
549template is associated with zero or more other templates that it may invoke by
550name; such associations are transitive and form a name space of templates.
551</p>
552<p>
553A template may use a template invocation to instantiate another associated
554template; see the explanation of the "template" action above. The name must be
555that of a template associated with the template that contains the invocation.
556</p>
557<h3 id="hdr-Nested_template_definitions">Nested template definitions</h3>
558<p>
559When parsing a template, another template may be defined and associated with the
560template being parsed. Template definitions must appear at the top level of the
561template, much like global variables in a Go program.
562</p>
563<p>
564The syntax of such definitions is to surround each template declaration with a
565"define" and "end" action.
566</p>
567<p>
568The define action names the template being created by providing a string
569constant. Here is a simple example:
570</p>
571<pre>`{{define "T1"}}ONE{{end}}
572{{define "T2"}}TWO{{end}}
573{{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}}
574{{template "T3"}}`
575</pre>
576<p>
577This defines two templates, T1 and T2, and a third T3 that invokes the other two
578when it is executed. Finally it invokes T3. If executed this template will
579produce the text
580</p>
581<pre>ONE TWO
582</pre>
583<p>
584By construction, a template may reside in only one association. If it's
585necessary to have a template addressable from multiple associations, the
586template definition must be parsed multiple times to create distinct *Template
587values, or must be copied with the Clone or AddParseTree method.
588</p>
589<p>
590Parse may be called multiple times to assemble the various associated templates;
591see the ParseFiles and ParseGlob functions and methods for simple ways to parse
592related templates stored in files.
593</p>
594<p>
595A template may be executed directly or through ExecuteTemplate, which executes
596an associated template identified by name. To invoke our example above, we
597might write,
598</p>
599<pre>err := tmpl.Execute(os.Stdout, "no data needed")
600if err != nil {
601 log.Fatalf("execution failed: %s", err)
602}
603</pre>
604<p>
605or to invoke a particular template explicitly by name,
606</p>
607<pre>err := tmpl.ExecuteTemplate(os.Stdout, "T2", "no data needed")
608if err != nil {
609 log.Fatalf("execution failed: %s", err)
610}
611</pre>
612
613
614 </div>
615 </div>
616
617 <div id="pkg-index" class="toggleVisible">
618 <div class="collapsed">
619 <h2 class="toggleButton" title="Click to show Index section">Index ▹</h2>
620 </div>
621 <div class="expanded">
622 <h2 class="toggleButton" title="Click to hide Index section">Index ▾</h2>
623
624 <!-- Table of contents for API; must be named manual-nav to turn off auto nav. -->
625 <div id="manual-nav">
626 <dl>
627
628
629
630
631 <dd><a href="#HTMLEscape">func HTMLEscape(w io.Writer, b []byte)</a></dd>
632
633
634 <dd><a href="#HTMLEscapeString">func HTMLEscapeString(s string) string</a></dd>
635
636
637 <dd><a href="#HTMLEscaper">func HTMLEscaper(args ...interface{}) string</a></dd>
638
639
640 <dd><a href="#IsTrue">func IsTrue(val interface{}) (truth, ok bool)</a></dd>
641
642
643 <dd><a href="#JSEscape">func JSEscape(w io.Writer, b []byte)</a></dd>
644
645
646 <dd><a href="#JSEscapeString">func JSEscapeString(s string) string</a></dd>
647
648
649 <dd><a href="#JSEscaper">func JSEscaper(args ...interface{}) string</a></dd>
650
651
652 <dd><a href="#URLQueryEscaper">func URLQueryEscaper(args ...interface{}) string</a></dd>
653
654
655
656 <dd><a href="#ExecError">type ExecError</a></dd>
657
658
659
660 <dd> <a href="#ExecError.Error">func (e ExecError) Error() string</a></dd>
661
662
663 <dd> <a href="#ExecError.Unwrap">func (e ExecError) Unwrap() error</a></dd>
664
665
666
667 <dd><a href="#FuncMap">type FuncMap</a></dd>
668
669
670
671
672 <dd><a href="#Template">type Template</a></dd>
673
674
675 <dd> <a href="#Must">func Must(t *Template, err error) *Template</a></dd>
676
677
678 <dd> <a href="#New">func New(name string) *Template</a></dd>
679
680
681 <dd> <a href="#ParseFiles">func ParseFiles(filenames ...string) (*Template, error)</a></dd>
682
683
684 <dd> <a href="#ParseGlob">func ParseGlob(pattern string) (*Template, error)</a></dd>
685
686
687
688 <dd> <a href="#Template.AddParseTree">func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)</a></dd>
689
690
691 <dd> <a href="#Template.Clone">func (t *Template) Clone() (*Template, error)</a></dd>
692
693
694 <dd> <a href="#Template.DefinedTemplates">func (t *Template) DefinedTemplates() string</a></dd>
695
696
697 <dd> <a href="#Template.Delims">func (t *Template) Delims(left, right string) *Template</a></dd>
698
699
700 <dd> <a href="#Template.Execute">func (t *Template) Execute(wr io.Writer, data interface{}) error</a></dd>
701
702
703 <dd> <a href="#Template.ExecuteTemplate">func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error</a></dd>
704
705
706 <dd> <a href="#Template.Funcs">func (t *Template) Funcs(funcMap FuncMap) *Template</a></dd>
707
708
709 <dd> <a href="#Template.Lookup">func (t *Template) Lookup(name string) *Template</a></dd>
710
711
712 <dd> <a href="#Template.Name">func (t *Template) Name() string</a></dd>
713
714
715 <dd> <a href="#Template.New">func (t *Template) New(name string) *Template</a></dd>
716
717
718 <dd> <a href="#Template.Option">func (t *Template) Option(opt ...string) *Template</a></dd>
719
720
721 <dd> <a href="#Template.Parse">func (t *Template) Parse(text string) (*Template, error)</a></dd>
722
723
724 <dd> <a href="#Template.ParseFiles">func (t *Template) ParseFiles(filenames ...string) (*Template, error)</a></dd>
725
726
727 <dd> <a href="#Template.ParseGlob">func (t *Template) ParseGlob(pattern string) (*Template, error)</a></dd>
728
729
730 <dd> <a href="#Template.Templates">func (t *Template) Templates() []*Template</a></dd>
731
732
733
734 </dl>
735 </div><!-- #manual-nav -->
736
737
738 <div id="pkg-examples">
739 <h3>Examples</h3>
740 <div class="js-expandAll expandAll collapsed">(Expand All)</div>
741 <dl>
742
743 <dd><a class="exampleLink" href="#example_Template">Template</a></dd>
744
745 <dd><a class="exampleLink" href="#example_Template_block">Template (Block)</a></dd>
746
747 <dd><a class="exampleLink" href="#example_Template_func">Template (Func)</a></dd>
748
749 <dd><a class="exampleLink" href="#example_Template_glob">Template (Glob)</a></dd>
750
751 <dd><a class="exampleLink" href="#example_Template_helpers">Template (Helpers)</a></dd>
752
753 <dd><a class="exampleLink" href="#example_Template_share">Template (Share)</a></dd>
754
755 </dl>
756 </div>
757
758
759
760 <h3>Package files</h3>
761 <p>
762 <span style="font-size:90%">
763
764 <a href="/src/text/template/doc.go">doc.go</a>
765
766 <a href="/src/text/template/exec.go">exec.go</a>
767
768 <a href="/src/text/template/funcs.go">funcs.go</a>
769
770 <a href="/src/text/template/helper.go">helper.go</a>
771
772 <a href="/src/text/template/option.go">option.go</a>
773
774 <a href="/src/text/template/template.go">template.go</a>
775
776 </span>
777 </p>
778
779 </div><!-- .expanded -->
780 </div><!-- #pkg-index -->
781
782
783
784
785
786
787 <h2 id="HTMLEscape">func <a href="/src/text/template/funcs.go?s=15725:15763#L574">HTMLEscape</a>
788 <a class="permalink" href="#HTMLEscape">¶</a>
789
790
791 </h2>
792 <pre>func HTMLEscape(w <a href="/pkg/io/">io</a>.<a href="/pkg/io/#Writer">Writer</a>, b []<a href="/pkg/builtin/#byte">byte</a>)</pre>
793 <p>
794HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.
795</p>
796
797
798
799
800
801
802 <h2 id="HTMLEscapeString">func <a href="/src/text/template/funcs.go?s=16202:16240#L602">HTMLEscapeString</a>
803 <a class="permalink" href="#HTMLEscapeString">¶</a>
804
805
806 </h2>
807 <pre>func HTMLEscapeString(s <a href="/pkg/builtin/#string">string</a>) <a href="/pkg/builtin/#string">string</a></pre>
808 <p>
809HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.
810</p>
811
812
813
814
815
816
817 <h2 id="HTMLEscaper">func <a href="/src/text/template/funcs.go?s=16504:16548#L614">HTMLEscaper</a>
818 <a class="permalink" href="#HTMLEscaper">¶</a>
819
820
821 </h2>
822 <pre>func HTMLEscaper(args ...interface{}) <a href="/pkg/builtin/#string">string</a></pre>
823 <p>
824HTMLEscaper returns the escaped HTML equivalent of the textual
825representation of its arguments.
826</p>
827
828
829
830
831
832
833 <h2 id="IsTrue">func <a href="/src/text/template/exec.go?s=8705:8750#L296">IsTrue</a>
834 <a class="permalink" href="#IsTrue">¶</a>
835
836 <span title="Added in Go 1.6">1.6</span>
837 </h2>
838 <pre>func IsTrue(val interface{}) (truth, ok <a href="/pkg/builtin/#bool">bool</a>)</pre>
839 <p>
840IsTrue reports whether the value is 'true', in the sense of not the zero of its type,
841and whether the value has a meaningful truth value. This is the definition of
842truth used by if and other such actions.
843</p>
844
845
846
847
848
849
850 <h2 id="JSEscape">func <a href="/src/text/template/funcs.go?s=16924:16960#L632">JSEscape</a>
851 <a class="permalink" href="#JSEscape">¶</a>
852
853
854 </h2>
855 <pre>func JSEscape(w <a href="/pkg/io/">io</a>.<a href="/pkg/io/#Writer">Writer</a>, b []<a href="/pkg/builtin/#byte">byte</a>)</pre>
856 <p>
857JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.
858</p>
859
860
861
862
863
864
865 <h2 id="JSEscapeString">func <a href="/src/text/template/funcs.go?s=17859:17895#L679">JSEscapeString</a>
866 <a class="permalink" href="#JSEscapeString">¶</a>
867
868
869 </h2>
870 <pre>func JSEscapeString(s <a href="/pkg/builtin/#string">string</a>) <a href="/pkg/builtin/#string">string</a></pre>
871 <p>
872JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.
873</p>
874
875
876
877
878
879
880 <h2 id="JSEscaper">func <a href="/src/text/template/funcs.go?s=18296:18338#L699">JSEscaper</a>
881 <a class="permalink" href="#JSEscaper">¶</a>
882
883
884 </h2>
885 <pre>func JSEscaper(args ...interface{}) <a href="/pkg/builtin/#string">string</a></pre>
886 <p>
887JSEscaper returns the escaped JavaScript equivalent of the textual
888representation of its arguments.
889</p>
890
891
892
893
894
895
896 <h2 id="URLQueryEscaper">func <a href="/src/text/template/funcs.go?s=18527:18575#L705">URLQueryEscaper</a>
897 <a class="permalink" href="#URLQueryEscaper">¶</a>
898
899
900 </h2>
901 <pre>func URLQueryEscaper(args ...interface{}) <a href="/pkg/builtin/#string">string</a></pre>
902 <p>
903URLQueryEscaper returns the escaped value of the textual representation of
904its arguments in a form suitable for embedding in a URL query.
905</p>
906
907
908
909
910
911
912
913 <h2 id="ExecError">type <a href="/src/text/template/exec.go?s=3110:3206#L105">ExecError</a>
914 <a class="permalink" href="#ExecError">¶</a>
915
916 <span title="Added in Go 1.6">1.6</span>
917 </h2>
918 <p>
919ExecError is the custom error type returned when Execute has an
920error evaluating its template. (If a write error occurs, the actual
921error is returned; it will not be of type ExecError.)
922</p>
923
924 <pre>type ExecError struct {
925<span id="ExecError.Name"></span> Name <a href="/pkg/builtin/#string">string</a> <span class="comment">// Name of template.</span>
926<span id="ExecError.Err"></span> Err <a href="/pkg/builtin/#error">error</a> <span class="comment">// Pre-formatted error.</span>
927}
928</pre>
929
930
931
932
933
934
935
936
937
938
939
940 <h3 id="ExecError.Error">func (ExecError) <a href="/src/text/template/exec.go?s=3208:3241#L110">Error</a>
941 <a class="permalink" href="#ExecError.Error">¶</a>
942
943 <span title="Added in Go 1.6">1.6</span>
944 </h3>
945 <pre>func (e <a href="#ExecError">ExecError</a>) Error() <a href="/pkg/builtin/#string">string</a></pre>
946
947
948
949
950
951 <h3 id="ExecError.Unwrap">func (ExecError) <a href="/src/text/template/exec.go?s=3269:3302#L114">Unwrap</a>
952 <a class="permalink" href="#ExecError.Unwrap">¶</a>
953
954 <span title="Added in Go 1.13">1.13</span>
955 </h3>
956 <pre>func (e <a href="#ExecError">ExecError</a>) Unwrap() <a href="/pkg/builtin/#error">error</a></pre>
957
958
959
960
961
962
963
964 <h2 id="FuncMap">type <a href="/src/text/template/funcs.go?s=1000:1035#L20">FuncMap</a>
965 <a class="permalink" href="#FuncMap">¶</a>
966
967
968 </h2>
969 <p>
970FuncMap is the type of the map defining the mapping from names to functions.
971Each function must have either a single return value, or two return values of
972which the second has type error. In that case, if the second (error)
973return value evaluates to non-nil during execution, execution terminates and
974Execute returns that error.
975</p>
976<p>
977When template execution invokes a function with an argument list, that list
978must be assignable to the function's parameter types. Functions meant to
979apply to arguments of arbitrary type can use parameters of type interface{} or
980of type reflect.Value. Similarly, functions meant to return a result of arbitrary
981type can return interface{} or reflect.Value.
982</p>
983
984 <pre>type FuncMap map[<a href="/pkg/builtin/#string">string</a>]interface{}</pre>
985
986
987
988
989
990
991
992
993
994
995
996
997
998 <h2 id="Template">type <a href="/src/text/template/template.go?s=859:956#L18">Template</a>
999 <a class="permalink" href="#Template">¶</a>
1000
1001
1002 </h2>
1003 <p>
1004Template is the representation of a parsed template. The *parse.Tree
1005field is exported only for use by html/template and should be treated
1006as unexported by all other clients.
1007</p>
1008
1009 <pre>type Template struct {
1010 *<a href="/pkg/text/template/parse/">parse</a>.<a href="/pkg/text/template/parse/#Tree">Tree</a>
1011 <span class="comment">// contains filtered or unexported fields</span>
1012}
1013</pre>
1014
1015
1016
1017
1018
1019 <div id="example_Template" class="toggle">
1020 <div class="collapsed">
1021 <p class="exampleHeading toggleButton">▹ <span class="text">Example</span></p>
1022 </div>
1023 <div class="expanded">
1024 <p class="exampleHeading toggleButton">▾ <span class="text">Example</span></p>
1025
1026
1027
1028 <div class="play">
1029 <div class="input"><textarea class="code" spellcheck="false">package main
1030
1031import (
1032 "log"
1033 "os"
1034 "text/template"
1035)
1036
1037func main() {
1038 // Define a template.
1039 const letter = `
1040Dear {{.Name}},
1041{{if .Attended}}
1042It was a pleasure to see you at the wedding.
1043{{- else}}
1044It is a shame you couldn't make it to the wedding.
1045{{- end}}
1046{{with .Gift -}}
1047Thank you for the lovely {{.}}.
1048{{end}}
1049Best wishes,
1050Josie
1051`
1052
1053 // Prepare some data to insert into the template.
1054 type Recipient struct {
1055 Name, Gift string
1056 Attended bool
1057 }
1058 var recipients = []Recipient{
1059 {"Aunt Mildred", "bone china tea set", true},
1060 {"Uncle John", "moleskin pants", false},
1061 {"Cousin Rodney", "", false},
1062 }
1063
1064 // Create a new template and parse the letter into it.
1065 t := template.Must(template.New("letter").Parse(letter))
1066
1067 // Execute the template for each recipient.
1068 for _, r := range recipients {
1069 err := t.Execute(os.Stdout, r)
1070 if err != nil {
1071 log.Println("executing template:", err)
1072 }
1073 }
1074
1075}
1076</textarea></div>
1077 <div class="output"><pre>Dear Aunt Mildred,
1078
1079It was a pleasure to see you at the wedding.
1080Thank you for the lovely bone china tea set.
1081
1082Best wishes,
1083Josie
1084
1085Dear Uncle John,
1086
1087It is a shame you couldn't make it to the wedding.
1088Thank you for the lovely moleskin pants.
1089
1090Best wishes,
1091Josie
1092
1093Dear Cousin Rodney,
1094
1095It is a shame you couldn't make it to the wedding.
1096
1097Best wishes,
1098Josie
1099</pre></div>
1100 <div class="buttons">
1101 <button class="Button Button--primary run" title="Run this code [shift-enter]">Run</button>
1102 <button class="Button fmt" title="Format this code">Format</button>
1103
1104 <button class="Button share" title="Share this code">Share</button>
1105
1106 </div>
1107 </div>
1108
1109 </div>
1110</div>
1111<div id="example_Template_block" class="toggle">
1112 <div class="collapsed">
1113 <p class="exampleHeading toggleButton">▹ <span class="text">Example (Block)</span></p>
1114 </div>
1115 <div class="expanded">
1116 <p class="exampleHeading toggleButton">▾ <span class="text">Example (Block)</span></p>
1117
1118
1119
1120 <div class="play">
1121 <div class="input"><textarea class="code" spellcheck="false">package main
1122
1123import (
1124 "log"
1125 "os"
1126 "strings"
1127 "text/template"
1128)
1129
1130func main() {
1131 const (
1132 master = `Names:{{block "list" .}}{{"\n"}}{{range .}}{{println "-" .}}{{end}}{{end}}`
1133 overlay = `{{define "list"}} {{join . ", "}}{{end}} `
1134 )
1135 var (
1136 funcs = template.FuncMap{"join": strings.Join}
1137 guardians = []string{"Gamora", "Groot", "Nebula", "Rocket", "Star-Lord"}
1138 )
1139 masterTmpl, err := template.New("master").Funcs(funcs).Parse(master)
1140 if err != nil {
1141 log.Fatal(err)
1142 }
1143 overlayTmpl, err := template.Must(masterTmpl.Clone()).Parse(overlay)
1144 if err != nil {
1145 log.Fatal(err)
1146 }
1147 if err := masterTmpl.Execute(os.Stdout, guardians); err != nil {
1148 log.Fatal(err)
1149 }
1150 if err := overlayTmpl.Execute(os.Stdout, guardians); err != nil {
1151 log.Fatal(err)
1152 }
1153}
1154</textarea></div>
1155 <div class="output"><pre>Names:
1156- Gamora
1157- Groot
1158- Nebula
1159- Rocket
1160- Star-Lord
1161Names: Gamora, Groot, Nebula, Rocket, Star-Lord
1162</pre></div>
1163 <div class="buttons">
1164 <button class="Button Button--primary run" title="Run this code [shift-enter]">Run</button>
1165 <button class="Button fmt" title="Format this code">Format</button>
1166
1167 <button class="Button share" title="Share this code">Share</button>
1168
1169 </div>
1170 </div>
1171
1172 </div>
1173</div>
1174<div id="example_Template_func" class="toggle">
1175 <div class="collapsed">
1176 <p class="exampleHeading toggleButton">▹ <span class="text">Example (Func)</span></p>
1177 </div>
1178 <div class="expanded">
1179 <p class="exampleHeading toggleButton">▾ <span class="text">Example (Func)</span></p>
1180 <p>This example demonstrates a custom function to process template text.
1181It installs the strings.Title function and uses it to
1182Make Title Text Look Good In Our Template's Output.
1183</p>
1184
1185
1186 <div class="play">
1187 <div class="input"><textarea class="code" spellcheck="false">package main
1188
1189import (
1190 "log"
1191 "os"
1192 "strings"
1193 "text/template"
1194)
1195
1196func main() {
1197 // First we create a FuncMap with which to register the function.
1198 funcMap := template.FuncMap{
1199 // The name "title" is what the function will be called in the template text.
1200 "title": strings.Title,
1201 }
1202
1203 // A simple template definition to test our function.
1204 // We print the input text several ways:
1205 // - the original
1206 // - title-cased
1207 // - title-cased and then printed with %q
1208 // - printed with %q and then title-cased.
1209 const templateText = `
1210Input: {{printf "%q" .}}
1211Output 0: {{title .}}
1212Output 1: {{title . | printf "%q"}}
1213Output 2: {{printf "%q" . | title}}
1214`
1215
1216 // Create a template, add the function map, and parse the text.
1217 tmpl, err := template.New("titleTest").Funcs(funcMap).Parse(templateText)
1218 if err != nil {
1219 log.Fatalf("parsing: %s", err)
1220 }
1221
1222 // Run the template to verify the output.
1223 err = tmpl.Execute(os.Stdout, "the go programming language")
1224 if err != nil {
1225 log.Fatalf("execution: %s", err)
1226 }
1227
1228}
1229</textarea></div>
1230 <div class="output"><pre>Input: "the go programming language"
1231Output 0: The Go Programming Language
1232Output 1: "The Go Programming Language"
1233Output 2: "The Go Programming Language"
1234</pre></div>
1235 <div class="buttons">
1236 <button class="Button Button--primary run" title="Run this code [shift-enter]">Run</button>
1237 <button class="Button fmt" title="Format this code">Format</button>
1238
1239 <button class="Button share" title="Share this code">Share</button>
1240
1241 </div>
1242 </div>
1243
1244 </div>
1245</div>
1246<div id="example_Template_glob" class="toggle">
1247 <div class="collapsed">
1248 <p class="exampleHeading toggleButton">▹ <span class="text">Example (Glob)</span></p>
1249 </div>
1250 <div class="expanded">
1251 <p class="exampleHeading toggleButton">▾ <span class="text">Example (Glob)</span></p>
1252 <p>Here we demonstrate loading a set of templates from a directory.
1253</p>
1254
1255
1256 <div class="play">
1257 <div class="input"><textarea class="code" spellcheck="false">package main
1258
1259import (
1260 "io"
1261 "io/ioutil"
1262 "log"
1263 "os"
1264 "path/filepath"
1265 "text/template"
1266)
1267
1268// templateFile defines the contents of a template to be stored in a file, for testing.
1269type templateFile struct {
1270 name string
1271 contents string
1272}
1273
1274func createTestDir(files []templateFile) string {
1275 dir, err := ioutil.TempDir("", "template")
1276 if err != nil {
1277 log.Fatal(err)
1278 }
1279 for _, file := range files {
1280 f, err := os.Create(filepath.Join(dir, file.name))
1281 if err != nil {
1282 log.Fatal(err)
1283 }
1284 defer f.Close()
1285 _, err = io.WriteString(f, file.contents)
1286 if err != nil {
1287 log.Fatal(err)
1288 }
1289 }
1290 return dir
1291}
1292
1293func main() {
1294 // Here we create a temporary directory and populate it with our sample
1295 // template definition files; usually the template files would already
1296 // exist in some location known to the program.
1297 dir := createTestDir([]templateFile{
1298 // T0.tmpl is a plain template file that just invokes T1.
1299 {"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`},
1300 // T1.tmpl defines a template, T1 that invokes T2.
1301 {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
1302 // T2.tmpl defines a template T2.
1303 {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
1304 })
1305 // Clean up after the test; another quirk of running as an example.
1306 defer os.RemoveAll(dir)
1307
1308 // pattern is the glob pattern used to find all the template files.
1309 pattern := filepath.Join(dir, "*.tmpl")
1310
1311 // Here starts the example proper.
1312 // T0.tmpl is the first name matched, so it becomes the starting template,
1313 // the value returned by ParseGlob.
1314 tmpl := template.Must(template.ParseGlob(pattern))
1315
1316 err := tmpl.Execute(os.Stdout, nil)
1317 if err != nil {
1318 log.Fatalf("template execution: %s", err)
1319 }
1320}
1321</textarea></div>
1322 <div class="output"><pre>T0 invokes T1: (T1 invokes T2: (This is T2))
1323</pre></div>
1324 <div class="buttons">
1325 <button class="Button Button--primary run" title="Run this code [shift-enter]">Run</button>
1326 <button class="Button fmt" title="Format this code">Format</button>
1327
1328 <button class="Button share" title="Share this code">Share</button>
1329
1330 </div>
1331 </div>
1332
1333 </div>
1334</div>
1335<div id="example_Template_helpers" class="toggle">
1336 <div class="collapsed">
1337 <p class="exampleHeading toggleButton">▹ <span class="text">Example (Helpers)</span></p>
1338 </div>
1339 <div class="expanded">
1340 <p class="exampleHeading toggleButton">▾ <span class="text">Example (Helpers)</span></p>
1341 <p>This example demonstrates one way to share some templates
1342and use them in different contexts. In this variant we add multiple driver
1343templates by hand to an existing bundle of templates.
1344</p>
1345
1346
1347 <div class="play">
1348 <div class="input"><textarea class="code" spellcheck="false">package main
1349
1350import (
1351 "io"
1352 "io/ioutil"
1353 "log"
1354 "os"
1355 "path/filepath"
1356 "text/template"
1357)
1358
1359// templateFile defines the contents of a template to be stored in a file, for testing.
1360type templateFile struct {
1361 name string
1362 contents string
1363}
1364
1365func createTestDir(files []templateFile) string {
1366 dir, err := ioutil.TempDir("", "template")
1367 if err != nil {
1368 log.Fatal(err)
1369 }
1370 for _, file := range files {
1371 f, err := os.Create(filepath.Join(dir, file.name))
1372 if err != nil {
1373 log.Fatal(err)
1374 }
1375 defer f.Close()
1376 _, err = io.WriteString(f, file.contents)
1377 if err != nil {
1378 log.Fatal(err)
1379 }
1380 }
1381 return dir
1382}
1383
1384func main() {
1385 // Here we create a temporary directory and populate it with our sample
1386 // template definition files; usually the template files would already
1387 // exist in some location known to the program.
1388 dir := createTestDir([]templateFile{
1389 // T1.tmpl defines a template, T1 that invokes T2.
1390 {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
1391 // T2.tmpl defines a template T2.
1392 {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
1393 })
1394 // Clean up after the test; another quirk of running as an example.
1395 defer os.RemoveAll(dir)
1396
1397 // pattern is the glob pattern used to find all the template files.
1398 pattern := filepath.Join(dir, "*.tmpl")
1399
1400 // Here starts the example proper.
1401 // Load the helpers.
1402 templates := template.Must(template.ParseGlob(pattern))
1403 // Add one driver template to the bunch; we do this with an explicit template definition.
1404 _, err := templates.Parse("{{define `driver1`}}Driver 1 calls T1: ({{template `T1`}})\n{{end}}")
1405 if err != nil {
1406 log.Fatal("parsing driver1: ", err)
1407 }
1408 // Add another driver template.
1409 _, err = templates.Parse("{{define `driver2`}}Driver 2 calls T2: ({{template `T2`}})\n{{end}}")
1410 if err != nil {
1411 log.Fatal("parsing driver2: ", err)
1412 }
1413 // We load all the templates before execution. This package does not require
1414 // that behavior but html/template's escaping does, so it's a good habit.
1415 err = templates.ExecuteTemplate(os.Stdout, "driver1", nil)
1416 if err != nil {
1417 log.Fatalf("driver1 execution: %s", err)
1418 }
1419 err = templates.ExecuteTemplate(os.Stdout, "driver2", nil)
1420 if err != nil {
1421 log.Fatalf("driver2 execution: %s", err)
1422 }
1423}
1424</textarea></div>
1425 <div class="output"><pre>Driver 1 calls T1: (T1 invokes T2: (This is T2))
1426Driver 2 calls T2: (This is T2)
1427</pre></div>
1428 <div class="buttons">
1429 <button class="Button Button--primary run" title="Run this code [shift-enter]">Run</button>
1430 <button class="Button fmt" title="Format this code">Format</button>
1431
1432 <button class="Button share" title="Share this code">Share</button>
1433
1434 </div>
1435 </div>
1436
1437 </div>
1438</div>
1439<div id="example_Template_share" class="toggle">
1440 <div class="collapsed">
1441 <p class="exampleHeading toggleButton">▹ <span class="text">Example (Share)</span></p>
1442 </div>
1443 <div class="expanded">
1444 <p class="exampleHeading toggleButton">▾ <span class="text">Example (Share)</span></p>
1445 <p>This example demonstrates how to use one group of driver
1446templates with distinct sets of helper templates.
1447</p>
1448
1449
1450 <div class="play">
1451 <div class="input"><textarea class="code" spellcheck="false">package main
1452
1453import (
1454 "io"
1455 "io/ioutil"
1456 "log"
1457 "os"
1458 "path/filepath"
1459 "text/template"
1460)
1461
1462// templateFile defines the contents of a template to be stored in a file, for testing.
1463type templateFile struct {
1464 name string
1465 contents string
1466}
1467
1468func createTestDir(files []templateFile) string {
1469 dir, err := ioutil.TempDir("", "template")
1470 if err != nil {
1471 log.Fatal(err)
1472 }
1473 for _, file := range files {
1474 f, err := os.Create(filepath.Join(dir, file.name))
1475 if err != nil {
1476 log.Fatal(err)
1477 }
1478 defer f.Close()
1479 _, err = io.WriteString(f, file.contents)
1480 if err != nil {
1481 log.Fatal(err)
1482 }
1483 }
1484 return dir
1485}
1486
1487func main() {
1488 // Here we create a temporary directory and populate it with our sample
1489 // template definition files; usually the template files would already
1490 // exist in some location known to the program.
1491 dir := createTestDir([]templateFile{
1492 // T0.tmpl is a plain template file that just invokes T1.
1493 {"T0.tmpl", "T0 ({{.}} version) invokes T1: ({{template `T1`}})\n"},
1494 // T1.tmpl defines a template, T1 that invokes T2. Note T2 is not defined
1495 {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
1496 })
1497 // Clean up after the test; another quirk of running as an example.
1498 defer os.RemoveAll(dir)
1499
1500 // pattern is the glob pattern used to find all the template files.
1501 pattern := filepath.Join(dir, "*.tmpl")
1502
1503 // Here starts the example proper.
1504 // Load the drivers.
1505 drivers := template.Must(template.ParseGlob(pattern))
1506
1507 // We must define an implementation of the T2 template. First we clone
1508 // the drivers, then add a definition of T2 to the template name space.
1509
1510 // 1. Clone the helper set to create a new name space from which to run them.
1511 first, err := drivers.Clone()
1512 if err != nil {
1513 log.Fatal("cloning helpers: ", err)
1514 }
1515 // 2. Define T2, version A, and parse it.
1516 _, err = first.Parse("{{define `T2`}}T2, version A{{end}}")
1517 if err != nil {
1518 log.Fatal("parsing T2: ", err)
1519 }
1520
1521 // Now repeat the whole thing, using a different version of T2.
1522 // 1. Clone the drivers.
1523 second, err := drivers.Clone()
1524 if err != nil {
1525 log.Fatal("cloning drivers: ", err)
1526 }
1527 // 2. Define T2, version B, and parse it.
1528 _, err = second.Parse("{{define `T2`}}T2, version B{{end}}")
1529 if err != nil {
1530 log.Fatal("parsing T2: ", err)
1531 }
1532
1533 // Execute the templates in the reverse order to verify the
1534 // first is unaffected by the second.
1535 err = second.ExecuteTemplate(os.Stdout, "T0.tmpl", "second")
1536 if err != nil {
1537 log.Fatalf("second execution: %s", err)
1538 }
1539 err = first.ExecuteTemplate(os.Stdout, "T0.tmpl", "first")
1540 if err != nil {
1541 log.Fatalf("first: execution: %s", err)
1542 }
1543
1544}
1545</textarea></div>
1546 <div class="output"><pre>T0 (second version) invokes T1: (T1 invokes T2: (T2, version B))
1547T0 (first version) invokes T1: (T1 invokes T2: (T2, version A))
1548</pre></div>
1549 <div class="buttons">
1550 <button class="Button Button--primary run" title="Run this code [shift-enter]">Run</button>
1551 <button class="Button fmt" title="Format this code">Format</button>
1552
1553 <button class="Button share" title="Share this code">Share</button>
1554
1555 </div>
1556 </div>
1557
1558 </div>
1559</div>
1560
1561
1562
1563
1564 <h3 id="Must">func <a href="/src/text/template/helper.go?s=576:619#L11">Must</a>
1565 <a class="permalink" href="#Must">¶</a>
1566
1567
1568 </h3>
1569 <pre>func Must(t *<a href="#Template">Template</a>, err <a href="/pkg/builtin/#error">error</a>) *<a href="#Template">Template</a></pre>
1570 <p>
1571Must is a helper that wraps a call to a function returning (*Template, error)
1572and panics if the error is non-nil. It is intended for use in variable
1573initializations such as
1574</p>
1575<pre>var t = template.Must(template.New("name").Parse("text"))
1576</pre>
1577
1578
1579
1580
1581 <h3 id="New">func <a href="/src/text/template/template.go?s=1022:1053#L27">New</a>
1582 <a class="permalink" href="#New">¶</a>
1583
1584
1585 </h3>
1586 <pre>func New(name <a href="/pkg/builtin/#string">string</a>) *<a href="#Template">Template</a></pre>
1587 <p>
1588New allocates a new, undefined template with the given name.
1589</p>
1590
1591
1592
1593
1594 <h3 id="ParseFiles">func <a href="/src/text/template/helper.go?s=1224:1279#L27">ParseFiles</a>
1595 <a class="permalink" href="#ParseFiles">¶</a>
1596
1597
1598 </h3>
1599 <pre>func ParseFiles(filenames ...<a href="/pkg/builtin/#string">string</a>) (*<a href="#Template">Template</a>, <a href="/pkg/builtin/#error">error</a>)</pre>
1600 <p>
1601ParseFiles creates a new Template and parses the template definitions from
1602the named files. The returned template's name will have the base name and
1603parsed contents of the first file. There must be at least one file.
1604If an error occurs, parsing stops and the returned *Template is nil.
1605</p>
1606<p>
1607When parsing multiple files with the same name in different directories,
1608the last one mentioned will be the one that results.
1609For instance, ParseFiles("a/foo", "b/foo") stores "b/foo" as the template
1610named "foo", while "a/foo" is unavailable.
1611</p>
1612
1613
1614
1615
1616 <h3 id="ParseGlob">func <a href="/src/text/template/helper.go?s=3809:3858#L93">ParseGlob</a>
1617 <a class="permalink" href="#ParseGlob">¶</a>
1618
1619
1620 </h3>
1621 <pre>func ParseGlob(pattern <a href="/pkg/builtin/#string">string</a>) (*<a href="#Template">Template</a>, <a href="/pkg/builtin/#error">error</a>)</pre>
1622 <p>
1623ParseGlob creates a new Template and parses the template definitions from
1624the files identified by the pattern. The files are matched according to the
1625semantics of filepath.Match, and the pattern must match at least one file.
1626The returned template will have the (base) name and (parsed) contents of the
1627first file matched by the pattern. ParseGlob is equivalent to calling
1628ParseFiles with the list of files matched by the pattern.
1629</p>
1630<p>
1631When parsing multiple files with the same name in different directories,
1632the last one mentioned will be the one that results.
1633</p>
1634
1635
1636
1637
1638
1639
1640 <h3 id="Template.AddParseTree">func (*Template) <a href="/src/text/template/template.go?s=3446:3527#L114">AddParseTree</a>
1641 <a class="permalink" href="#Template.AddParseTree">¶</a>
1642
1643
1644 </h3>
1645 <pre>func (t *<a href="#Template">Template</a>) AddParseTree(name <a href="/pkg/builtin/#string">string</a>, tree *<a href="/pkg/text/template/parse/">parse</a>.<a href="/pkg/text/template/parse/#Tree">Tree</a>) (*<a href="#Template">Template</a>, <a href="/pkg/builtin/#error">error</a>)</pre>
1646 <p>
1647AddParseTree adds parse tree for template with given name and associates it with t.
1648If the template does not already exist, it will create a new one.
1649If the template does exist, it will be replaced.
1650</p>
1651
1652
1653
1654
1655
1656 <h3 id="Template.Clone">func (*Template) <a href="/src/text/template/template.go?s=2497:2542#L75">Clone</a>
1657 <a class="permalink" href="#Template.Clone">¶</a>
1658
1659
1660 </h3>
1661 <pre>func (t *<a href="#Template">Template</a>) Clone() (*<a href="#Template">Template</a>, <a href="/pkg/builtin/#error">error</a>)</pre>
1662 <p>
1663Clone returns a duplicate of the template, including all associated
1664templates. The actual representation is not copied, but the name space of
1665associated templates is, so further calls to Parse in the copy will add
1666templates to the copy but not to the original. Clone can be used to prepare
1667common templates and use them with variant definitions for other templates
1668by adding the variants after the clone is made.
1669</p>
1670
1671
1672
1673
1674
1675 <h3 id="Template.DefinedTemplates">func (*Template) <a href="/src/text/template/exec.go?s=6556:6600#L219">DefinedTemplates</a>
1676 <a class="permalink" href="#Template.DefinedTemplates">¶</a>
1677
1678 <span title="Added in Go 1.5">1.5</span>
1679 </h3>
1680 <pre>func (t *<a href="#Template">Template</a>) DefinedTemplates() <a href="/pkg/builtin/#string">string</a></pre>
1681 <p>
1682DefinedTemplates returns a string listing the defined templates,
1683prefixed by the string "; defined templates are: ". If there are none,
1684it returns the empty string. For generating an error message here
1685and in html/template.
1686</p>
1687
1688
1689
1690
1691
1692 <h3 id="Template.Delims">func (*Template) <a href="/src/text/template/template.go?s=4440:4495#L146">Delims</a>
1693 <a class="permalink" href="#Template.Delims">¶</a>
1694
1695
1696 </h3>
1697 <pre>func (t *<a href="#Template">Template</a>) Delims(left, right <a href="/pkg/builtin/#string">string</a>) *<a href="#Template">Template</a></pre>
1698 <p>
1699Delims sets the action delimiters to the specified strings, to be used in
1700subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template
1701definitions will inherit the settings. An empty delimiter stands for the
1702corresponding default: {{ or }}.
1703The return value is the template, so calls can be chained.
1704</p>
1705
1706
1707
1708
1709
1710 <h3 id="Template.Execute">func (*Template) <a href="/src/text/template/exec.go?s=5823:5887#L193">Execute</a>
1711 <a class="permalink" href="#Template.Execute">¶</a>
1712
1713
1714 </h3>
1715 <pre>func (t *<a href="#Template">Template</a>) Execute(wr <a href="/pkg/io/">io</a>.<a href="/pkg/io/#Writer">Writer</a>, data interface{}) <a href="/pkg/builtin/#error">error</a></pre>
1716 <p>
1717Execute applies a parsed template to the specified data object,
1718and writes the output to wr.
1719If an error occurs executing the template or writing its output,
1720execution stops, but partial results may already have been written to
1721the output writer.
1722A template may be executed safely in parallel, although if parallel
1723executions share a Writer the output may be interleaved.
1724</p>
1725<p>
1726If data is a reflect.Value, the template applies to the concrete
1727value that the reflect.Value holds, as in fmt.Print.
1728</p>
1729
1730
1731
1732
1733
1734 <h3 id="Template.ExecuteTemplate">func (*Template) <a href="/src/text/template/exec.go?s=5003:5088#L172">ExecuteTemplate</a>
1735 <a class="permalink" href="#Template.ExecuteTemplate">¶</a>
1736
1737
1738 </h3>
1739 <pre>func (t *<a href="#Template">Template</a>) ExecuteTemplate(wr <a href="/pkg/io/">io</a>.<a href="/pkg/io/#Writer">Writer</a>, name <a href="/pkg/builtin/#string">string</a>, data interface{}) <a href="/pkg/builtin/#error">error</a></pre>
1740 <p>
1741ExecuteTemplate applies the template associated with t that has the given name
1742to the specified data object and writes the output to wr.
1743If an error occurs executing the template or writing its output,
1744execution stops, but partial results may already have been written to
1745the output writer.
1746A template may be executed safely in parallel, although if parallel
1747executions share a Writer the output may be interleaved.
1748</p>
1749
1750
1751
1752
1753
1754 <h3 id="Template.Funcs">func (*Template) <a href="/src/text/template/template.go?s=4963:5014#L159">Funcs</a>
1755 <a class="permalink" href="#Template.Funcs">¶</a>
1756
1757
1758 </h3>
1759 <pre>func (t *<a href="#Template">Template</a>) Funcs(funcMap <a href="#FuncMap">FuncMap</a>) *<a href="#Template">Template</a></pre>
1760 <p>
1761Funcs adds the elements of the argument map to the template's function map.
1762It must be called before the template is parsed.
1763It panics if a value in the map is not a function with appropriate return
1764type or if the name cannot be used syntactically as a function in a template.
1765It is legal to overwrite elements of the map. The return value is the template,
1766so calls can be chained.
1767</p>
1768
1769
1770
1771
1772
1773 <h3 id="Template.Lookup">func (*Template) <a href="/src/text/template/template.go?s=5314:5362#L170">Lookup</a>
1774 <a class="permalink" href="#Template.Lookup">¶</a>
1775
1776
1777 </h3>
1778 <pre>func (t *<a href="#Template">Template</a>) Lookup(name <a href="/pkg/builtin/#string">string</a>) *<a href="#Template">Template</a></pre>
1779 <p>
1780Lookup returns the template with the given name that is associated with t.
1781It returns nil if there is no such template or the template has no definition.
1782</p>
1783
1784
1785
1786
1787
1788 <h3 id="Template.Name">func (*Template) <a href="/src/text/template/template.go?s=1155:1187#L36">Name</a>
1789 <a class="permalink" href="#Template.Name">¶</a>
1790
1791
1792 </h3>
1793 <pre>func (t *<a href="#Template">Template</a>) Name() <a href="/pkg/builtin/#string">string</a></pre>
1794 <p>
1795Name returns the name of the template.
1796</p>
1797
1798
1799
1800
1801
1802 <h3 id="Template.New">func (*Template) <a href="/src/text/template/template.go?s=1612:1657#L47">New</a>
1803 <a class="permalink" href="#Template.New">¶</a>
1804
1805
1806 </h3>
1807 <pre>func (t *<a href="#Template">Template</a>) New(name <a href="/pkg/builtin/#string">string</a>) *<a href="#Template">Template</a></pre>
1808 <p>
1809New allocates a new, undefined template associated with the given one and with the same
1810delimiters. The association, which is transitive, allows one template to
1811invoke another with a {{template}} action.
1812</p>
1813<p>
1814Because associated templates share underlying data, template construction
1815cannot be done safely in parallel. Once the templates are constructed, they
1816can be executed in parallel.
1817</p>
1818
1819
1820
1821
1822
1823 <h3 id="Template.Option">func (*Template) <a href="/src/text/template/option.go?s=1400:1450#L32">Option</a>
1824 <a class="permalink" href="#Template.Option">¶</a>
1825
1826 <span title="Added in Go 1.5">1.5</span>
1827 </h3>
1828 <pre>func (t *<a href="#Template">Template</a>) Option(opt ...<a href="/pkg/builtin/#string">string</a>) *<a href="#Template">Template</a></pre>
1829 <p>
1830Option sets options for the template. Options are described by
1831strings, either a simple string or "key=value". There can be at
1832most one equals sign in an option string. If the option string
1833is unrecognized or otherwise invalid, Option panics.
1834</p>
1835<p>
1836Known options:
1837</p>
1838<p>
1839missingkey: Control the behavior during execution if a map is
1840indexed with a key that is not present in the map.
1841</p>
1842<pre>"missingkey=default" or "missingkey=invalid"
1843 The default behavior: Do nothing and continue execution.
1844 If printed, the result of the index operation is the string
1845 "<no value>".
1846"missingkey=zero"
1847 The operation returns the zero value for the map type's element.
1848"missingkey=error"
1849 Execution stops immediately with an error.
1850</pre>
1851
1852
1853
1854
1855
1856 <h3 id="Template.Parse">func (*Template) <a href="/src/text/template/template.go?s=5984:6040#L187">Parse</a>
1857 <a class="permalink" href="#Template.Parse">¶</a>
1858
1859
1860 </h3>
1861 <pre>func (t *<a href="#Template">Template</a>) Parse(text <a href="/pkg/builtin/#string">string</a>) (*<a href="#Template">Template</a>, <a href="/pkg/builtin/#error">error</a>)</pre>
1862 <p>
1863Parse parses text as a template body for t.
1864Named template definitions ({{define ...}} or {{block ...}} statements) in text
1865define additional templates associated with t and are removed from the
1866definition of t itself.
1867</p>
1868<p>
1869Templates can be redefined in successive calls to Parse.
1870A template definition with a body containing only white space and comments
1871is considered empty and will not replace an existing template's body.
1872This allows using Parse to add new named template definitions without
1873overwriting the main template body.
1874</p>
1875
1876
1877
1878
1879
1880 <h3 id="Template.ParseFiles">func (*Template) <a href="/src/text/template/helper.go?s=2001:2070#L42">ParseFiles</a>
1881 <a class="permalink" href="#Template.ParseFiles">¶</a>
1882
1883
1884 </h3>
1885 <pre>func (t *<a href="#Template">Template</a>) ParseFiles(filenames ...<a href="/pkg/builtin/#string">string</a>) (*<a href="#Template">Template</a>, <a href="/pkg/builtin/#error">error</a>)</pre>
1886 <p>
1887ParseFiles parses the named files and associates the resulting templates with
1888t. If an error occurs, parsing stops and the returned template is nil;
1889otherwise it is t. There must be at least one file.
1890Since the templates created by ParseFiles are named by the base
1891names of the argument files, t should usually have the name of one
1892of the (base) names of the files. If it does not, depending on t's
1893contents before calling ParseFiles, t.Execute may fail. In that
1894case use t.ExecuteTemplate to execute a valid template.
1895</p>
1896<p>
1897When parsing multiple files with the same name in different directories,
1898the last one mentioned will be the one that results.
1899</p>
1900
1901
1902
1903
1904
1905 <h3 id="Template.ParseGlob">func (*Template) <a href="/src/text/template/helper.go?s=4383:4446#L105">ParseGlob</a>
1906 <a class="permalink" href="#Template.ParseGlob">¶</a>
1907
1908
1909 </h3>
1910 <pre>func (t *<a href="#Template">Template</a>) ParseGlob(pattern <a href="/pkg/builtin/#string">string</a>) (*<a href="#Template">Template</a>, <a href="/pkg/builtin/#error">error</a>)</pre>
1911 <p>
1912ParseGlob parses the template definitions in the files identified by the
1913pattern and associates the resulting templates with t. The files are matched
1914according to the semantics of filepath.Match, and the pattern must match at
1915least one file. ParseGlob is equivalent to calling t.ParseFiles with the
1916list of files matched by the pattern.
1917</p>
1918<p>
1919When parsing multiple files with the same name in different directories,
1920the last one mentioned will be the one that results.
1921</p>
1922
1923
1924
1925
1926
1927 <h3 id="Template.Templates">func (*Template) <a href="/src/text/template/template.go?s=3884:3926#L129">Templates</a>
1928 <a class="permalink" href="#Template.Templates">¶</a>
1929
1930
1931 </h3>
1932 <pre>func (t *<a href="#Template">Template</a>) Templates() []*<a href="#Template">Template</a></pre>
1933 <p>
1934Templates returns a slice of defined templates associated with t.
1935</p>
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951 <h2 id="pkg-subdirectories">Subdirectories</h2>
1952
1953 <div class="pkg-dir">
1954 <table>
1955 <tr>
1956 <th class="pkg-name">Name</th>
1957 <th class="pkg-synopsis">Synopsis</th>
1958 </tr>
1959
1960
1961 <tr>
1962 <td colspan="2"><a href="..">..</a></td>
1963 </tr>
1964
1965
1966
1967 <tr>
1968
1969 <td class="pkg-name" style="padding-left: 0px;">
1970 <a href="parse/">parse</a>
1971 </td>
1972
1973 <td class="pkg-synopsis">
1974 Package parse builds parse trees for templates as defined by text/template and html/template.
1975 </td>
1976 </tr>
1977
1978 </table>
1979 </div>
1980
1981
1982
1983</div><!-- .container -->
1984</main><!-- #page -->
1985<footer>
1986 <div class="Footer Footer--wide">
1987 <img class="Footer-gopher" src="/lib/godoc/images/footer-gopher.jpg" alt="The Go Gopher">
1988 <ul class="Footer-links">
1989 <li class="Footer-link"><a href="/doc/copyright.html">Copyright</a></li>
1990 <li class="Footer-link"><a href="/doc/tos.html">Terms of Service</a></li>
1991 <li class="Footer-link"><a href="http://www.google.com/intl/en/policies/privacy/">Privacy Policy</a></li>
1992 <li class="Footer-link"><a href="http://golang.org/issues/new?title=x/website:" target="_blank" rel="noopener">Report a website issue</a></li>
1993 </ul>
1994 <a class="Footer-supportedBy" href="https://google.com">Supported by Google</a>
1995 </div>
1996</footer>
1997
1998<script>
1999(function() {
2000 var ga = document.createElement("script"); ga.type = "text/javascript"; ga.async = true;
2001 ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";
2002 var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ga, s);
2003})();
2004</script>