# package template
`import "text/template"`
template包實現了數據驅動的用于生成文本輸出的模板。
如果要生成HTML格式的輸出,參見html/template包,該包提供了和本包相同的接口,但會自動將輸出轉化為安全的HTML格式輸出,可以抵抗一些網絡攻擊。
通過將模板應用于一個數據結構(即該數據結構作為模板的參數)來執行,來獲得輸出。模板中的注釋引用數據接口的元素(一般如結構體的字段或者字典的鍵)來控制執行過程和獲取需要呈現的值。模板執行時會遍歷結構并將指針表示為'.'(稱之為"dot")指向運行過程中數據結構的當前位置的值。
用作模板的輸入文本必須是utf-8編碼的文本。"Action"—數據運算和控制單位—由"{{"和"}}"界定;在Action之外的所有文本都不做修改的拷貝到輸出中。Action內部不能有換行,但注釋可以有換行。
經解析生成模板后,一個模板可以安全的并發執行。
下面是一個簡單的例子,可以打印"17 of wool"。
```
type Inventory struct {
Material string
Count uint
}
sweaters := Inventory{"wool", 17}
tmpl, err := template.New("test").Parse("{{.Count}} of {{.Material}}")
if err != nil { panic(err) }
err = tmpl.Execute(os.Stdout, sweaters)
if err != nil { panic(err) }
```
更復雜的例子在下面。
### Actions
下面是一個action(動作)的列表。"Arguments"和"pipelines"代表數據的執行結果,細節定義在后面。
```
{{/* a comment */}}
注釋,執行時會忽略。可以多行。注釋不能嵌套,并且必須緊貼分界符始止,就像這里表示的一樣。
{{pipeline}}
pipeline的值的默認文本表示會被拷貝到輸出里。
{{if pipeline}} T1 {{end}}
如果pipeline的值為empty,不產生輸出,否則輸出T1執行結果。不改變dot的值。
Empty值包括false、0、任意nil指針或者nil接口,任意長度為0的數組、切片、字典。
{{if pipeline}} T1 {{else}} T0 {{end}}
如果pipeline的值為empty,輸出T0執行結果,否則輸出T1執行結果。不改變dot的值。
{{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
用于簡化if-else鏈條,else action可以直接包含另一個if;等價于:
{{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}}
{{range pipeline}} T1 {{end}}
pipeline的值必須是數組、切片、字典或者通道。
如果pipeline的值其長度為0,不會有任何輸出;
否則dot依次設為數組、切片、字典或者通道的每一個成員元素并執行T1;
如果pipeline的值為字典,且鍵可排序的基本類型,元素也會按鍵的順序排序。
{{range pipeline}} T1 {{else}} T0 {{end}}
pipeline的值必須是數組、切片、字典或者通道。
如果pipeline的值其長度為0,不改變dot的值并執行T0;否則會修改dot并執行T1。
{{template "name"}}
執行名為name的模板,提供給模板的參數為nil,如模板不存在輸出為""
{{template "name" pipeline}}
執行名為name的模板,提供給模板的參數為pipeline的值。
{{with pipeline}} T1 {{end}}
如果pipeline為empty不產生輸出,否則將dot設為pipeline的值并執行T1。不修改外面的dot。
{{with pipeline}} T1 {{else}} T0 {{end}}
如果pipeline為empty,不改變dot并執行T0,否則dot設為pipeline的值并執行T1。
```
### Arguments
參數代表一個簡單的,由下面的某一條表示的值:
```
- go語法的布爾值、字符串、字符、整數、浮點數、虛數、復數,視為無類型字面常數,字符串不能跨行
- 關鍵字nil,代表一個go的無類型的nil值
- 字符'.'(句點,用時不加單引號),代表dot的值
- 變量名,以美元符號起始加上(可為空的)字母和數字構成的字符串,如:$piOver2和$;
執行結果為變量的值,變量參見下面的介紹
- 結構體數據的字段名,以句點起始,如:.Field;
執行結果為字段的值,支持鏈式調用:.Field1.Field2;
字段也可以在變量上使用(包括鏈式調用):$x.Field1.Field2;
- 字典類型數據的鍵名;以句點起始,如:.Key;
執行結果是該鍵在字典中對應的成員元素的值;
鍵也可以和字段配合做鏈式調用,深度不限:.Field1.Key1.Field2.Key2;
雖然鍵也必須是字母和數字構成的標識字符串,但不需要以大寫字母起始;
鍵也可以用于變量(包括鏈式調用):$x.key1.key2;
- 數據的無參數方法名,以句點為起始,如:.Method;
執行結果為dot調用該方法的返回值,dot.Method();
該方法必須有1到2個返回值,如果有2個則后一個必須是error接口類型;
如果有2個返回值的方法返回的error非nil,模板執行會中斷并返回給調用模板執行者該錯誤;
方法可和字段、鍵配合做鏈式調用,深度不限:.Field1.Key1.Method1.Field2.Key2.Method2;
方法也可以在變量上使用(包括鏈式調用):$x.Method1.Field;
- 無參數的函數名,如:fun;
執行結果是調用該函數的返回值fun();對返回值的要求和方法一樣;函數和函數名細節參見后面。
- 上面某一條的實例加上括弧(用于分組)
執行結果可以訪問其字段或者鍵對應的值:
print (.F1 arg1) (.F2 arg2)
(.StructValuedMethod "arg").Field
```
Arguments可以是任何類型:如果是指針,在必要時會自動表示為指針指向的值;如果執行結果生成了一個函數類型的值,如結構體的函數類型字段,該函數不會自動調用,但可以在if等action里視為真。如果要調用它,使用call函數,參見下面。
Pipeline是一個(可能是鏈狀的)command序列。Command可以是一個簡單值(argument)或者對函數或者方法的(可以有多個參數的)調用:
```
Argument
執行結果是argument的執行結果
.Method [Argument...]
方法可以獨立調用或者位于鏈式調用的末端,不同于鏈式調用中間的方法,可以使用參數;
執行結果是使用給出的參數調用該方法的返回值:dot.Method(Argument1, etc.);
functionName [Argument...]
執行結果是使用給定的參數調用函數名指定的函數的返回值:function(Argument1, etc.);
```
### Pipelines
pipeline通常是將一個command序列分割開,再使用管道符'|'連接起來(但不使用管道符的command序列也可以視為一個管道)。在一個鏈式的pipeline里,每個command的結果都作為下一個command的最后一個參數。pipeline最后一個command的輸出作為整個管道執行的結果。
command的輸出可以是1到2個值,如果是2個后一個必須是error接口類型。如果error類型返回值非nil,模板執行會中止并將該錯誤返回給執行模板的調用者。
### Variables
Action里可以初始化一個變量來捕獲管道的執行結果。初始化語法如下:
```
$variable := pipeline
```
其中$variable是變量的名字。聲明變量的action不會產生任何輸出。
如果"range" action初始化了1個變量,該變量設置為迭代器的每一個成員元素,如果初始化了逗號分隔的2個變量:
```
range $index, $element := pipeline
```
這時,$index和$element分別設置為數組/切片的索引或者字典的鍵,以及對應的成員元素。注意這和go range從句只有一個參數時設置為索引/鍵不同!
一個變量的作用域只到聲明它的控制結構("if"、"with"、"range")的"end"為止,如果不是在控制結構里聲明會直到模板結束為止。子模板的調用不會從調用它的位置(作用域)繼承變量。
模板開始執行時,$會設置為傳遞給Execute方法的參數,就是說,dot的初始值。
### Examples
下面是一些單行模板,展示了pipeline和變量。所有都生成加引號的單詞"output":
```
{{"\"output\""}}
字符串常量
{{`"output"`}}
原始字符串常量
{{printf "%q" "output"}}
函數調用
{{"output" | printf "%q"}}
函數調用,最后一個參數來自前一個command的返回值
{{printf "%q" (print "out" "put")}}
加括號的參數
{{"put" | printf "%s%s" "out" | printf "%q"}}
玩出花的管道的鏈式調用
{{"output" | printf "%s" | printf "%q"}}
管道的鏈式調用
{{with "output"}}{{printf "%q" .}}{{end}}
使用dot的with action
{{with $x := "output" | printf "%q"}}{{$x}}{{end}}
創建并使用變量的with action
{{with $x := "output"}}{{printf "%q" $x}}{{end}}
將變量使用在另一個action的with action
{{with $x := "output"}}{{$x | printf "%q"}}{{end}}
以管道形式將變量使用在另一個action的with action
```
### Functions
執行模板時,函數從兩個函數字典中查找:首先是模板函數字典,然后是全局函數字典。一般不在模板內定義函數,而是使用Funcs方法添加函數到模板里。
預定義的全局函數如下:
```
and
函數返回它的第一個empty參數或者最后一個參數;
就是說"and x y"等價于"if x then y else x";所有參數都會執行;
or
返回第一個非empty參數或者最后一個參數;
亦即"or x y"等價于"if x then x else y";所有參數都會執行;
not
返回它的單個參數的布爾值的否定
len
返回它的參數的整數類型長度
index
執行結果為第一個參數以剩下的參數為索引/鍵指向的值;
如"index x 1 2 3"返回x[1][2][3]的值;每個被索引的主體必須是數組、切片或者字典。
print
即fmt.Sprint
printf
即fmt.Sprintf
println
即fmt.Sprintln
html
返回其參數文本表示的HTML逸碼等價表示。
urlquery
返回其參數文本表示的可嵌入URL查詢的逸碼等價表示。
js
返回其參數文本表示的JavaScript逸碼等價表示。
call
執行結果是調用第一個參數的返回值,該參數必須是函數類型,其余參數作為調用該函數的參數;
如"call .X.Y 1 2"等價于go語言里的dot.X.Y(1, 2);
其中Y是函數類型的字段或者字典的值,或者其他類似情況;
call的第一個參數的執行結果必須是函數類型的值(和預定義函數如print明顯不同);
該函數類型值必須有1到2個返回值,如果有2個則后一個必須是error接口類型;
如果有2個返回值的方法返回的error非nil,模板執行會中斷并返回給調用模板執行者該錯誤;
```
布爾函數會將任何類型的零值視為假,其余視為真。
下面是定義為函數的二元比較運算的集合:
```
eq 如果arg1 == arg2則返回真
ne 如果arg1 != arg2則返回真
lt 如果arg1 < arg2則返回真
le 如果arg1 <= arg2則返回真="" gt="" 如果arg1=""> arg2則返回真
ge 如果arg1 >= arg2則返回真
```
為了簡化多參數相等檢測,eq(只有eq)可以接受2個或更多個參數,它會將第一個參數和其余參數依次比較,返回下式的結果:
```
arg1==arg2 || arg1==arg3 || arg1==arg4 ...
```
(和go的||不一樣,不做惰性運算,所有參數都會執行)
比較函數只適用于基本類型(或重定義的基本類型,如"type Celsius float32")。它們實現了go語言規則的值的比較,但具體的類型和大小會忽略掉,因此任意類型有符號整數值都可以互相比較;任意類型無符號整數值都可以互相比較;等等。但是,整數和浮點數不能互相比較。
### Associated templates
每一個模板在創建時都要用一個字符串命名。同時,每一個模板都會和0或多個模板關聯,并可以使用它們的名字調用這些模板;這種關聯可以傳遞,并形成一個模板的名字空間。
一個模板可以通過模板調用實例化另一個模板;參見上面的"template" action。name必須是包含模板調用的模板相關聯的模板的名字。
### Nested template definitions
當解析模板時,可以定義另一個模板,該模板會和當前解析的模板相關聯。模板必須定義在當前模板的最頂層,就像go程序里的全局變量一樣。
這種定義模板的語法是將每一個子模板的聲明放在"define"和"end" action內部。
define action使用給出的字符串常數給模板命名,舉例如下:
```
`{{define "T1"}}ONE{{end}}
{{define "T2"}}TWO{{end}}
{{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}}
{{template "T3"}}`
```
它定義了兩個模板T1和T2,第三個模板T3在執行時調用這兩個模板;最后該模板調用了T3。輸出結果是:
```
ONE TWO
```
采用這種方法,一個模板只能從屬于一個關聯。如果需要讓一個模板可以被多個關聯查找到;模板定義必須多次解析以創建不同的\*Template?值,或者必須使用Clone或AddParseTree方法進行拷貝。
可能需要多次調用Parse函數以集合多個相關的模板;參見ParseFiles和ParseGlob函數和方法,它們提供了簡便的途徑去解析保存在文件中的存在關聯的模板。
一個模板可以直接調用或者通過ExecuteTemplate方法調用指定名字的相關聯的模板;我們可以這樣調用模板:
```
err := tmpl.Execute(os.Stdout, "no data needed")
if err != nil {
log.Fatalf("execution failed: %s", err)
}
```
或顯式的指定模板的名字來調用:
```
err := tmpl.ExecuteTemplate(os.Stdout, "T2", "no data needed")
if err != nil {
log.Fatalf("execution failed: %s", err)
}
```
## Index
* [func HTMLEscape(w io.Writer, b []byte)](#HTMLEscape)
* [func HTMLEscapeString(s string) string](#HTMLEscapeString)
* [func HTMLEscaper(args ...interface{}) string](#HTMLEscaper)
* [func JSEscape(w io.Writer, b []byte)](#JSEscape)
* [func JSEscapeString(s string) string](#JSEscapeString)
* [func JSEscaper(args ...interface{}) string](#JSEscaper)
* [func URLQueryEscaper(args ...interface{}) string](#URLQueryEscaper)
* [type FuncMap](#FuncMap)
* [type Template](#Template)
* [func Must(t \*Template, err error) \*Template](#Must)
* [func New(name string) \*Template](#New)
* [func ParseFiles(filenames ...string) (\*Template, error)](#ParseFiles)
* [func ParseGlob(pattern string) (\*Template, error)](#ParseGlob)
* [func (t \*Template) Name() string](#Template.Name)
* [func (t \*Template) Delims(left, right string) \*Template](#Template.Delims)
* [func (t \*Template) Funcs(funcMap FuncMap) \*Template](#Template.Funcs)
* [func (t \*Template) Clone() (\*Template, error)](#Template.Clone)
* [func (t \*Template) Lookup(name string) \*Template](#Template.Lookup)
* [func (t \*Template) Templates() []\*Template](#Template.Templates)
* [func (t \*Template) New(name string) \*Template](#Template.New)
* [func (t \*Template) AddParseTree(name string, tree \*parse.Tree) (\*Template, error)](#Template.AddParseTree)
* [func (t \*Template) Parse(text string) (\*Template, error)](#Template.Parse)
* [func (t \*Template) ParseFiles(filenames ...string) (\*Template, error)](#Template.ParseFiles)
* [func (t \*Template) ParseGlob(pattern string) (\*Template, error)](#Template.ParseGlob)
* [func (t \*Template) Execute(wr io.Writer, data interface{}) (err error)](#Template.Execute)
* [func (t \*Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error](#Template.ExecuteTemplate)
### Examples
* [Template](#example-Template)
* [Template (Func)](#example-Template--Func)
* [Template (Glob)](#example-Template--Glob)
* [Template (Helpers)](#example-Template--Helpers)
* [Template (Share)](#example-Template--Share)
## func [HTMLEscape](https://github.com/golang/go/blob/master/src/text/template/funcs.go#L425 "View Source")
```
func HTMLEscape(w io.Writer, b []byte)
```
函數向w中寫入b的HTML轉義等價表示。
## func [HTMLEscapeString](https://github.com/golang/go/blob/master/src/text/template/funcs.go#L451 "View Source")
```
func HTMLEscapeString(s string) string
```
返回s的HTML轉義等價表示字符串。
## func [HTMLEscaper](https://github.com/golang/go/blob/master/src/text/template/funcs.go#L463 "View Source")
```
func HTMLEscaper(args ...interface{}) string
```
函數返回其所有參數文本表示的HTML轉義等價表示字符串。
## func [JSEscape](https://github.com/golang/go/blob/master/src/text/template/funcs.go#L481 "View Source")
```
func JSEscape(w io.Writer, b []byte)
```
函數向w中寫入b的JavaScript轉義等價表示。
## func [JSEscapeString](https://github.com/golang/go/blob/master/src/text/template/funcs.go#L528 "View Source")
```
func JSEscapeString(s string) string
```
返回s的JavaScript轉義等價表示字符串。
## func [JSEscaper](https://github.com/golang/go/blob/master/src/text/template/funcs.go#L548 "View Source")
```
func JSEscaper(args ...interface{}) string
```
函數返回其所有參數文本表示的JavaScript轉義等價表示字符串。
## func [URLQueryEscaper](https://github.com/golang/go/blob/master/src/text/template/funcs.go#L554 "View Source")
```
func URLQueryEscaper(args ...interface{}) string
```
函數返回其所有參數文本表示的可以嵌入URL查詢的轉義等價表示字符串。
## type [FuncMap](https://github.com/golang/go/blob/master/src/text/template/funcs.go#L24 "View Source")
```
type FuncMap map[string]interface{}
```
FuncMap類型定義了函數名字符串到函數的映射,每個函數都必須有1到2個返回值,如果有2個則后一個必須是error接口類型;如果有2個返回值的方法返回的error非nil,模板執行會中斷并返回給調用者該錯誤。
## type [Template](https://github.com/golang/go/blob/master/src/text/template/template.go#L26 "View Source")
```
type Template struct {
*parse.Tree
// 內含隱藏或非導出字段
}
```
代表一個解析好的模板,\*parse.Tree字段僅僅是暴露給html/template包使用的,因此其他人應該視字段未導出。
Example
```
// Define a template.
const letter = `
Dear {{.Name}},
{{if .Attended}}
It was a pleasure to see you at the wedding.{{else}}
It is a shame you couldn't make it to the wedding.{{end}}
{{with .Gift}}Thank you for the lovely {{.}}.
{{end}}
Best wishes,
Josie
`
// Prepare some data to insert into the template.
type Recipient struct {
Name, Gift string
Attended bool
}
var recipients = []Recipient{
{"Aunt Mildred", "bone china tea set", true},
{"Uncle John", "moleskin pants", false},
{"Cousin Rodney", "", false},
}
// Create a new template and parse the letter into it.
t := template.Must(template.New("letter").Parse(letter))
// Execute the template for each recipient.
for _, r := range recipients {
err := t.Execute(os.Stdout, r)
if err != nil {
log.Println("executing template:", err)
}
}
```
Output:
```
Dear Aunt Mildred,
It was a pleasure to see you at the wedding.
Thank you for the lovely bone china tea set.
Best wishes,
Josie
Dear Uncle John,
It is a shame you couldn't make it to the wedding.
Thank you for the lovely moleskin pants.
Best wishes,
Josie
Dear Cousin Rodney,
It is a shame you couldn't make it to the wedding.
Best wishes,
Josie
```
Example (Func)
```
// First we create a FuncMap with which to register the function.
funcMap := template.FuncMap{
// The name "title" is what the function will be called in the template text.
"title": strings.Title,
}
// A simple template definition to test our function.
// We print the input text several ways:
// - the original
// - title-cased
// - title-cased and then printed with %q
// - printed with %q and then title-cased.
const templateText = `
Input: {{printf "%q" .}}
Output 0: {{title .}}
Output 1: {{title . | printf "%q"}}
Output 2: {{printf "%q" . | title}}
`
// Create a template, add the function map, and parse the text.
tmpl, err := template.New("titleTest").Funcs(funcMap).Parse(templateText)
if err != nil {
log.Fatalf("parsing: %s", err)
}
// Run the template to verify the output.
err = tmpl.Execute(os.Stdout, "the go programming language")
if err != nil {
log.Fatalf("execution: %s", err)
}
```
Output:
```
Input: "the go programming language"
Output 0: The Go Programming Language
Output 1: "The Go Programming Language"
Output 2: "The Go Programming Language"
```
Example (Glob)
```
// Here we create a temporary directory and populate it with our sample
// template definition files; usually the template files would already
// exist in some location known to the program.
dir := createTestDir([]templateFile{
// T0.tmpl is a plain template file that just invokes T1.
{"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`},
// T1.tmpl defines a template, T1 that invokes T2.
{"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
// T2.tmpl defines a template T2.
{"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
})
// Clean up after the test; another quirk of running as an example.
defer os.RemoveAll(dir)
// pattern is the glob pattern used to find all the template files.
pattern := filepath.Join(dir, "*.tmpl")
// Here starts the example proper.
// T0.tmpl is the first name matched, so it becomes the starting template,
// the value returned by ParseGlob.
tmpl := template.Must(template.ParseGlob(pattern))
err := tmpl.Execute(os.Stdout, nil)
if err != nil {
log.Fatalf("template execution: %s", err)
}
```
Output:
```
T0 invokes T1: (T1 invokes T2: (This is T2))
```
Example (Helpers)
```
// Here we create a temporary directory and populate it with our sample
// template definition files; usually the template files would already
// exist in some location known to the program.
dir := createTestDir([]templateFile{
// T1.tmpl defines a template, T1 that invokes T2.
{"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
// T2.tmpl defines a template T2.
{"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
})
// Clean up after the test; another quirk of running as an example.
defer os.RemoveAll(dir)
// pattern is the glob pattern used to find all the template files.
pattern := filepath.Join(dir, "*.tmpl")
// Here starts the example proper.
// Load the helpers.
templates := template.Must(template.ParseGlob(pattern))
// Add one driver template to the bunch; we do this with an explicit template definition.
_, err := templates.Parse("{{define `driver1`}}Driver 1 calls T1: ({{template `T1`}})\n{{end}}")
if err != nil {
log.Fatal("parsing driver1: ", err)
}
// Add another driver template.
_, err = templates.Parse("{{define `driver2`}}Driver 2 calls T2: ({{template `T2`}})\n{{end}}")
if err != nil {
log.Fatal("parsing driver2: ", err)
}
// We load all the templates before execution. This package does not require
// that behavior but html/template's escaping does, so it's a good habit.
err = templates.ExecuteTemplate(os.Stdout, "driver1", nil)
if err != nil {
log.Fatalf("driver1 execution: %s", err)
}
err = templates.ExecuteTemplate(os.Stdout, "driver2", nil)
if err != nil {
log.Fatalf("driver2 execution: %s", err)
}
```
Output:
```
Driver 1 calls T1: (T1 invokes T2: (This is T2))
Driver 2 calls T2: (This is T2)
```
Example (Share)
```
// Here we create a temporary directory and populate it with our sample
// template definition files; usually the template files would already
// exist in some location known to the program.
dir := createTestDir([]templateFile{
// T0.tmpl is a plain template file that just invokes T1.
{"T0.tmpl", "T0 ({{.}} version) invokes T1: ({{template `T1`}})\n"},
// T1.tmpl defines a template, T1 that invokes T2\. Note T2 is not defined
{"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
})
// Clean up after the test; another quirk of running as an example.
defer os.RemoveAll(dir)
// pattern is the glob pattern used to find all the template files.
pattern := filepath.Join(dir, "*.tmpl")
// Here starts the example proper.
// Load the drivers.
drivers := template.Must(template.ParseGlob(pattern))
// We must define an implementation of the T2 template. First we clone
// the drivers, then add a definition of T2 to the template name space.
// 1\. Clone the helper set to create a new name space from which to run them.
first, err := drivers.Clone()
if err != nil {
log.Fatal("cloning helpers: ", err)
}
// 2\. Define T2, version A, and parse it.
_, err = first.Parse("{{define `T2`}}T2, version A{{end}}")
if err != nil {
log.Fatal("parsing T2: ", err)
}
// Now repeat the whole thing, using a different version of T2.
// 1\. Clone the drivers.
second, err := drivers.Clone()
if err != nil {
log.Fatal("cloning drivers: ", err)
}
// 2\. Define T2, version B, and parse it.
_, err = second.Parse("{{define `T2`}}T2, version B{{end}}")
if err != nil {
log.Fatal("parsing T2: ", err)
}
// Execute the templates in the reverse order to verify the
// first is unaffected by the second.
err = second.ExecuteTemplate(os.Stdout, "T0.tmpl", "second")
if err != nil {
log.Fatalf("second execution: %s", err)
}
err = first.ExecuteTemplate(os.Stdout, "T0.tmpl", "first")
if err != nil {
log.Fatalf("first: execution: %s", err)
}
```
Output:
```
T0 (second version) invokes T1: (T1 invokes T2: (T2, version B))
T0 (first version) invokes T1: (T1 invokes T2: (T2, version A))
```
### func [Must](https://github.com/golang/go/blob/master/src/text/template/helper.go#L21 "View Source")
```
func Must(t *Template, err error) *Template
```
Must函數用于包裝返回(\*Template, error)的函數/方法調用,它會在err非nil時panic,一般用于變量初始化:
```
var t = template.Must(template.New("name").Parse("text"))
```
### func [New](https://github.com/golang/go/blob/master/src/text/template/template.go#L35 "View Source")
```
func New(name string) *Template
```
創建一個名為name的模板。
### func [ParseFiles](https://github.com/golang/go/blob/master/src/text/template/helper.go#L32 "View Source")
```
func ParseFiles(filenames ...string) (*Template, error)
```
ParseFiles函數創建一個模板并解析filenames指定的文件里的模板定義。返回的模板的名字是第一個文件的文件名(不含擴展名),內容為解析后的第一個文件的內容。至少要提供一個文件。如果發生錯誤,會停止解析并返回nil。
### func [ParseGlob](https://github.com/golang/go/blob/master/src/text/template/helper.go#L85 "View Source")
```
func ParseGlob(pattern string) (*Template, error)
```
ParseGlob創建一個模板并解析匹配pattern的文件(參見glob規則)里的模板定義。返回的模板的名字是第一個匹配的文件的文件名(不含擴展名),內容為解析后的第一個文件的內容。至少要存在一個匹配的文件。如果發生錯誤,會停止解析并返回nil。ParseGlob等價于使用匹配pattern的文件的列表為參數調用ParseFiles。
### func (\*Template) [Name](https://github.com/golang/go/blob/master/src/text/template/template.go#L42 "View Source")
```
func (t *Template) Name() string
```
返回模板t的名字。
### func (\*Template) [Delims](https://github.com/golang/go/blob/master/src/text/template/template.go#L136 "View Source")
```
func (t *Template) Delims(left, right string) *Template
```
Delims方法用于設置action的分界字符串,應用于之后的Parse、ParseFiles、ParseGlob方法。嵌套模板定義會繼承這種分界符設置。空字符串分界符表示相應的默認分界符:{{或}}。返回值就是t,以便進行鏈式調用。
### func (\*Template) [Funcs](https://github.com/golang/go/blob/master/src/text/template/template.go#L146 "View Source")
```
func (t *Template) Funcs(funcMap FuncMap) *Template
```
Funcs方法向模板t的函數字典里加入參數funcMap內的鍵值對。如果funcMap某個鍵值對的值不是函數類型或者返回值不符合要求會panic。但是,可以對t函數列表的成員進行重寫。方法返回t以便進行鏈式調用。
### func (\*Template) [Clone](https://github.com/golang/go/blob/master/src/text/template/template.go#L74 "View Source")
```
func (t *Template) Clone() (*Template, error)
```
Clone方法返回模板的一個副本,包括所有相關聯的模板。模板的底層表示樹并未拷貝,而是拷貝了命名空間,因此拷貝調用Parse方法不會修改原模板的命名空間。Clone方法用于準備模板的公用部分,向拷貝中加入其他關聯模板后再進行使用。
### func (\*Template) [Lookup](https://github.com/golang/go/blob/master/src/text/template/template.go#L155 "View Source")
```
func (t *Template) Lookup(name string) *Template
```
Lookup方法返回與t關聯的名為name的模板,如果沒有這個模板返回nil。
### func (\*Template) [Templates](https://github.com/golang/go/blob/master/src/text/template/template.go#L119 "View Source")
```
func (t *Template) Templates() []*Template
```
Templates方法返回與t相關聯的模板的切片,包括t自己。
### func (\*Template) [New](https://github.com/golang/go/blob/master/src/text/template/template.go#L49 "View Source")
```
func (t *Template) New(name string) *Template
```
New方法創建一個和t關聯的名字為name的模板并返回它。這種可以傳遞的關聯允許一個模板使用template action調用另一個模板。
### func (\*Template) [AddParseTree](https://github.com/golang/go/blob/master/src/text/template/template.go#L107 "View Source")
```
func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)
```
AddParseTree方法使用name和tree創建一個模板并使它和t相關聯。
### func (\*Template) [Parse](https://github.com/golang/go/blob/master/src/text/template/template.go#L169 "View Source")
```
func (t *Template) Parse(text string) (*Template, error)
```
Parse方法將字符串text解析為模板。嵌套定義的模板會關聯到最頂層的t。Parse可以多次調用,但只有第一次調用可以包含空格、注釋和模板定義之外的文本。如果后面的調用在解析后仍剩余文本會引發錯誤、返回nil且丟棄剩余文本;如果解析得到的模板已有相關聯的同名模板,會覆蓋掉原模板。
### func (\*Template) [ParseFiles](https://github.com/golang/go/blob/master/src/text/template/helper.go#L39 "View Source")
```
func (t *Template) ParseFiles(filenames ...string) (*Template, error)
```
ParseGlob方法解析filenames指定的文件里的模板定義并將解析結果與t關聯。如果發生錯誤,會停止解析并返回nil,否則返回(t, nil)。至少要提供一個文件。
### func (\*Template) [ParseGlob](https://github.com/golang/go/blob/master/src/text/template/helper.go#L94 "View Source")
```
func (t *Template) ParseGlob(pattern string) (*Template, error)
```
ParseFiles方法解析匹配pattern的文件里的模板定義并將解析結果與t關聯。如果發生錯誤,會停止解析并返回nil,否則返回(t, nil)。至少要存在一個匹配的文件。
### func (\*Template) [Execute](https://github.com/golang/go/blob/master/src/text/template/exec.go#L129 "View Source")
```
func (t *Template) Execute(wr io.Writer, data interface{}) (err error)
```
Execute方法將解析好的模板應用到data上,并將輸出寫入wr。如果執行時出現錯誤,會停止執行,但有可能已經寫入wr部分數據。模板可以安全的并發執行。
### func (\*Template) [ExecuteTemplate](https://github.com/golang/go/blob/master/src/text/template/exec.go#L115 "View Source")
```
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error
```
ExecuteTemplate方法類似Execute,但是使用名為name的t關聯的模板產生輸出。
- 庫
- package achive
- package tar
- package zip
- package bufio
- package builtin
- package bytes
- package compress
- package bzip2
- package flate
- package gzip
- package lzw
- package zlib
- package container
- package heap
- package list
- package ring
- package crypto
- package aes
- package cipher
- package des
- package dsa
- package ecdsa
- package elliptic
- package hmac
- package md5
- package rand
- package rc4
- package rsa
- package sha1
- package sha256
- package sha512
- package subtle
- package tls
- package x509
- package pkix
- package database
- package sql
- package driver
- package encoding
- package ascii85
- package asn1
- package base32
- package base64
- package binary
- package csv
- package gob
- package hex
- package json
- package pem
- package xml
- package errors
- package expvar
- package flag
- package fmt
- package go
- package doc
- package format
- package parser
- package printer
- package hash
- package adler32
- package crc32
- package crc64
- package fnv
- package html
- package template
- package image
- package color
- package palette
- package draw
- package gif
- package jpeg
- package png
- package index
- package suffixarray
- package io
- package ioutil
- package log
- package syslog
- package math
- package big
- package cmplx
- package rand
- package mime
- package multipart
- package net
- package http
- package cgi
- package cookiejar
- package fcgi
- package httptest
- package httputil
- package pprof
- package mail
- package rpc
- package jsonrpc
- package smtp
- package textproto
- package url
- package os
- package exec
- package signal
- package user
- package path
- package filepath
- package reflect
- package regexp
- package runtime
- package cgo
- package debug
- package pprof
- package race
- package sort
- package strconv
- package strings
- package sync
- package atomic
- package text
- package scanner
- package tabwriter
- package template
- package time
- package unicode
- package utf16
- package utf8
- package unsafe