{% raw %}
# package template
`import "html/template"`
template包(html/template)實現了數據驅動的模板,用于生成可對抗代碼注入的安全HTML輸出。本包提供了和text/template包相同的接口,無論何時當輸出是HTML的時候都應使用本包。
此處的文檔關注本包的安全特性。至于如何使用模板,請參照text/template包。
### Introduction
本包是對[text/template](http://godoc.org/text/template)包的包裝,兩個包提供的模板API幾無差別,可以安全的隨意替換兩包。
```
tmpl, err := template.New("name").Parse(...)
// 省略錯誤檢測
err = tmpl.Execute(out, data)
```
如果成功創建了tmpl,tmpl現在是注入安全的了。否則err將返回ErrorCode里定義的某個錯誤。即使成功生成了模板,執行時仍可能導致ErrorCode里定義的錯誤。
HTML模板將數據視為明文文本,必須經過編碼以便安全的嵌入HTML文檔。轉義操作會參考上下文,因此action可以出現在JavaScript、CSS、URI上下文環境里。
本包使用的安全模型假設模板的作者是可信任的,但用于執行的數據不可信。更多細節參見下面。
示例:
```
import "text/template"
...
t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")
```
生成:
```
Hello, <script>alert('you have been pwned')</script>!
```
但在html/template包里會根據上下文自動轉義:
```
import "html/template"
...
t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")
```
生成安全的轉義后HTML輸出:
```
Hello, <script>alert('you have been pwned')</script>!
```
### Contexts
本包可以理解HTML、CSS、JavaScript和URI。它會給每一個簡單的action pipeline都添加處理函數,如下例:
```
<a href="/search?q={{.}}">{{.}}</a>
```
在解析時每個{{.}}都會在必要時重寫添加轉義函數,此例中會修改為:
```
<a href="/search?q={{. | urlquery}}">{{. | html}}</a>
```
### Errors
細節請參見ErrorCode類型的文檔。
### A fuller picture
本包剩余部分的注釋第一次閱讀時可以跳過;這些部分包括理解轉碼文本和錯誤信息的必要細節。多數使用者無需理解這些細節。
### Contexts
假設{{.}}是`O'Reilly: How are <i>you</i>?`,下表展示了{{.}}用于左側模板時的輸出:
```
Context {{.}} After
{{.}} O'Reilly: How are <i>you</i>?
<a title='{{.}}'> O'Reilly: How are you?
<a href="/{{.}}"> O'Reilly: How are %3ci%3eyou%3c/i%3e?
<a href="?q={{.}}"> O'Reilly%3a%20How%20are%3ci%3e...%3f
<a onx='f("{{.}}")'> O\x27Reilly: How are \x3ci\x3eyou...?
<a onx='f({{.}})'> "O\x27Reilly: How are \x3ci\x3eyou...?"
<a onx='pattern = /{{.}}/;'> O\x27Reilly: How are \x3ci\x3eyou...\x3f
```
如果用在不安全的上下文里,值就可能被過濾掉:
```
Context {{.}} After
<a href="{{.}}"> #ZgotmplZ
```
因為"O'Reilly:"不是一個可以接受的協議名,如"http:"。
如果{{.}}是一個無害的詞匯,如`left`,那么它就可以出現在更多地方。
```
Context {{.}} After
{{.}} left
<a title='{{.}}'> left
<a href='{{.}}'> left
<a href='/{{.}}'> left
<a href='?dir={{.}}'> left
<a style="border-{{.}}: 4px"> left
<a style="align: {{.}}"> left
<a style="background: '{{.}}'> left
<a style="background: url('{{.}}')> left
<style>p.{{.}} {color:red}</style> left
```
如果{{.}}是非字符串類型的值,可以用于JavaScript上下文環境里:
```
struct{A,B string}{ "foo", "bar" }
```
將該值應用在在轉義后的模板里:
```
<script>var pair = {{.}};</script>
```
模板輸出為:
```
<script>var pair = {"A": "foo", "B": "bar"};</script>
```
請參見json包來理解非字符串內容是如何序列化并嵌入JavaScript里的。
### Typed Strings
本包默認所有的pipeline都生成明文字符串,它會在必要時添加轉義pipeline階段以安全并正確的將明文字符串嵌入輸出的文本里。
當用于執行的數據不是明文字符串時,你可以通過顯式改變數據的類型以避免其被錯誤的轉義。
類型HTML、JS、URL和其他content.go里定義的類型可以保持不被轉義的安全內容。
模板:
```
Hello, {{.}}!
```
可以采用如下調用:
```
tmpl.Execute(out, HTML(`<b>World</b>`))
```
來輸出:
```
Hello, <b>World</b>!
```
而不是:
```
Hello, <b>World<b>!
```
如果{{.}}是一個內建類型字符串就會產生該輸出。
### Security Model
本包里安全的定義參加如下網頁:
[http://js-quasis-libraries-and-repl.googlecode.com/svn/trunk/safetemplate.html#problem_definition](http://js-quasis-libraries-and-repl.googlecode.com/svn/trunk/safetemplate.html#problem_definition)
本包假設模板作者可信而執行數據不可信,目標是在保證安全性的前提下保證效率:
結構保留特性:“……當模板作者用安全的模板語言寫了一個HTML標簽時,不管數據的值為何瀏覽器都會將輸出的相應部分解釋為標簽,該情況在其他結構里也成立,如屬性邊界以及JS和CSS邊界。”
代碼影響特性:“……只有模板作者指定的代碼能作為注入模板輸出到頁面的結果執行,所有模板作者指定的代碼都應如此。”
最少驚訝特性:“一個熟悉HTML、CSS、JS的開發者(或代碼閱讀者),應可以正確的推斷出{{.}}會如何轉義。”
## Index
* [type ErrorCode](#ErrorCode)
* [type Error](#Error)
* [func (e \*Error) Error() string](#Error.Error)
* [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 HTML](#HTML)
* [type HTMLAttr](#HTMLAttr)
* [type JS](#JS)
* [type JSStr](#JSStr)
* [type CSS](#CSS)
* [type URL](#URL)
* [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(src 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{}) error](#Template.Execute)
* [func (t \*Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error](#Template.ExecuteTemplate)
## type [ErrorCode](https://github.com/golang/go/blob/master/src/html/template/error.go#L24 "View Source")
```
type ErrorCode int
```
ErrorCode是代表錯誤種類的錯誤碼。
```
const (
// OK表示沒有出錯
OK ErrorCode = iota
// 當上下文環境有歧義時導致ErrAmbigContext:
// 舉例:
// <a href="{{if .C}}/path/{{else}}/search?q={{end}}{{.X}}"&rt;
// 說明:
// {{.X}}的URL上下文環境有歧義,因為根據{{.C}}的值,
// 它可以是URL的后綴,或者是查詢的參數。
// 將{{.X}}移動到如下情況可以消除歧義:
// <a href="{{if .C}}/path/{{.X}}{{else}}/search?q={{.X}}{{end}}"&rt;
ErrAmbigContext
// 期望空白、屬性名、標簽結束標志而沒有時,標簽名或無引號標簽值包含非法字符時,
// 會導致ErrBadHTML;舉例:
// <a href = /search?q=foo&rt;
// <href=foo&rt;
// <form na<e=...&rt;
// <option selected<
// 討論:
// 一般是因為HTML元素輸入了錯誤的標簽名、屬性名或者未用引號的屬性值,導致解析失敗
// 將所有的屬性都用引號括起來是最好的策略
ErrBadHTML
// {{if}}等分支不在相同上下文開始和結束時,導致ErrBranchEnd
// 示例:
// {{if .C}}<a href="{{end}}{{.X}}
// 討論:
// html/template包會靜態的檢驗{{if}}、{{range}}或{{with}}的每一個分支,
// 以對后續的pipeline進行轉義。該例出現了歧義,{{.X}}可能是HTML文本節點,
// 或者是HTML屬性值的URL的前綴,{{.X}}的上下文環境可以確定如何轉義,但該
// 上下文環境卻是由運行時{{.C}}的值決定的,不能在編譯期獲知。
// 這種問題一般是因為缺少引號或者角括號引起的,另一些則可以通過重構將兩個上下文
// 放進if、range、with的不同分支里來避免,如果問題出現在參數長度一定非0的
// {{range}}的分支里,可以通過添加無效{{else}}分支解決。
ErrBranchEnd
// 如果以非文本上下文結束,則導致ErrEndContext
// 示例:
// <div
// <div title="no close quote&rt;
// <script>f()
// 討論:
// 執行模板必須生成HTML的一個文檔片段,以未閉合標簽結束的模板都會引發本錯誤。
// 不用在HTML上下文或者生成不完整片段的模板不應直接執行。
// {{define "main"}} <script&rt;{{template "helper"}}</script> {{end}}
// {{define "helper"}} document.write(' <div title=" ') {{end}}
// 模板"helper"不能生成合法的文檔片段,所以不直接執行,用js生成。
ErrEndContext
// 調用不存在的模板時導致ErrNoSuchTemplate
// 示例:
// {{define "main"}}<div {{template "attrs"}}&rt;{{end}}
// {{define "attrs"}}href="{{.URL}}"{{end}}
// 討論:
// html/template包略過模板調用計算上下文環境。
// 此例中,當被"main"模板調用時,"attrs"模板的{{.URL}}必須視為一個URL;
// 但如果解析"main"時,"attrs"還未被定義,就會導致本錯誤
ErrNoSuchTemplate
// 不能計算輸出位置的上下文環境時,導致ErrOutputContext
// 示例:
// {{define "t"}}{{if .T}}{{template "t" .T}}{{end}}{{.H}}",{{end}}
// 討論:
// 一個遞歸的模板,其起始和結束的上下文環境不同時;
// 不能計算出可信的輸出位置上下文環境時,就可能導致本錯誤。
// 檢查各個命名模板是否有錯誤;
// 如果模板不應在命名的起始上下文環境調用,檢查在不期望上下文環境中對該模板的調用;
// 或者將遞歸模板重構為非遞歸模板;
ErrOutputContext
// 尚未支持JS正則表達式插入字符集
// 示例:
// <script>var pattern = /foo[{{.Chars}}]/</script&rt;
// 討論:
// html/template不支持向JS正則表達式里插入字面值字符集
ErrPartialCharset
// 部分轉義序列尚未支持
// 示例:
// <script>alert("\{{.X}}")</script&rt;
// 討論:
// html/template包不支持緊跟在反斜杠后面的action
// 這一般是錯誤的,有更好的解決方法,例如:
// <script>alert("{{.X}}")</script&rt;
// 可以工作,如果{{.X}}是部分轉義序列,如"xA0",
// 可以將整個序列標記為安全文本:JSStr(`\xA0`)
ErrPartialEscape
// range循環的重入口出錯,導致ErrRangeLoopReentry
// 示例:
// <script>var x = [{{range .}}'{{.}},{{end}}]</script&rt;
// 討論:
// 如果range的迭代部分導致其結束于上一次循環的另一上下文,將不會有唯一的上下文環境
// 此例中,缺少一個引號,因此無法確定{{.}}是存在于一個JS字符串里,還是一個JS值文本里。
// 第二次迭代生成類似下面的輸出:
// <script>var x = ['firstValue,'secondValue]</script&rt;
ErrRangeLoopReentry
// 斜杠可以開始一個除法或者正則表達式
// 示例:
// <script&rt;
// {{if .C}}var x = 1{{end}}
// /-{{.N}}/i.test(x) ? doThis : doThat();
// </script&rt;
// 討論:
// 上例可以生成`var x = 1/-2/i.test(s)...`,其中第一個斜杠作為除號;
// 或者它也可以生成`/-2/i.test(s)`,其中第一個斜杠生成一個正則表達式字面值
// 檢查分支中是否缺少分號,或者使用括號來明確你的意圖
ErrSlashAmbig
)
```
我們為轉義模板時的所有錯誤都定義了錯誤碼,但經過轉義修正的模板仍可能在運行時出錯:
輸出"ZgotmplZ"的例子:
```
<img src="{{.X}}">
其中{{.X}}執行結果為`javascript:...`
```
討論:
```
"ZgotmplZ"是一個特殊值,表示運行時在CSS或URL上下文環境生成的不安全內容。本例的輸出為:
<img src="#ZgotmplZ">
如果數據來源可信,請轉換內容類型來避免被濾除:URL(`javascript:...`)
```
## type [Error](https://github.com/golang/go/blob/master/src/html/template/error.go#L12 "View Source")
```
type Error struct {
// ErrorCode描述錯誤的種類
ErrorCode ErrorCode
// Name是發生錯誤的模板的名字
Name string
// Line是錯誤位置在模板原文中的行號或者0
Line int
// Description是供調試者閱讀的錯誤描述
Description string
}
```
Error描述在模板轉義時出現的錯誤。
### func (\*Error) [Error](https://github.com/golang/go/blob/master/src/html/template/error.go#L184 "View Source")
```
func (e *Error) Error() string
```
## func [HTMLEscape](https://github.com/golang/go/blob/master/src/html/template/escape.go#L780 "View Source")
```
func HTMLEscape(w io.Writer, b []byte)
```
函數向w中寫入b的HTML轉義等價表示。
## func [HTMLEscapeString](https://github.com/golang/go/blob/master/src/html/template/escape.go#L785 "View Source")
```
func HTMLEscapeString(s string) string
```
返回s的HTML轉義等價表示字符串。
## func [HTMLEscaper](https://github.com/golang/go/blob/master/src/html/template/escape.go#L791 "View Source")
```
func HTMLEscaper(args ...interface{}) string
```
函數返回其所有參數文本表示的HTML轉義等價表示字符串。
## func [JSEscape](https://github.com/golang/go/blob/master/src/html/template/escape.go#L796 "View Source")
```
func JSEscape(w io.Writer, b []byte)
```
函數向w中寫入b的JavaScript轉義等價表示。
## func [JSEscapeString](https://github.com/golang/go/blob/master/src/html/template/escape.go#L801 "View Source")
```
func JSEscapeString(s string) string
```
返回s的JavaScript轉義等價表示字符串。
## func [JSEscaper](https://github.com/golang/go/blob/master/src/html/template/escape.go#L807 "View Source")
```
func JSEscaper(args ...interface{}) string
```
函數返回其所有參數文本表示的JavaScript轉義等價表示字符串。
## func [URLQueryEscaper](https://github.com/golang/go/blob/master/src/html/template/escape.go#L813 "View Source")
```
func URLQueryEscaper(args ...interface{}) string
```
函數返回其所有參數文本表示的可以嵌入URL查詢的轉義等價表示字符串。
## type [FuncMap](https://github.com/golang/go/blob/master/src/html/template/template.go#L261 "View Source")
```
type FuncMap map[string]interface{}
```
FuncMap類型定義了函數名字符串到函數的映射,每個函數都必須有1到2個返回值,如果有2個則后一個必須是error接口類型;如果有2個返回值的方法返回的error非nil,模板執行會中斷并返回給調用者該錯誤。該類型拷貝自text/template包的同名類型,因此不需要導入該包以使用該類型。
## type [HTML](https://github.com/golang/go/blob/master/src/html/template/content.go#L27 "View Source")
```
type HTML string
```
HTML用于封裝一個已知安全的HTML文檔片段。它不應被第三方使用,也不能用于含有未閉合的標簽或注釋的HTML文本。該類型適用于封裝一個效果良好的HTML生成器生成的HTML文本或者本包模板的輸出的文本。
## type [HTMLAttr](https://github.com/golang/go/blob/master/src/html/template/content.go#L31 "View Source")
```
type HTMLAttr string
```
HTMLAttr用來封裝一個來源可信的HTML屬性,如` dir="ltr"`。
## type [JS](https://github.com/golang/go/blob/master/src/html/template/content.go#L40 "View Source")
```
type JS string
```
JS用于封裝一個已知安全的EcmaScript5表達式,如`(x + y * z())`。模板作者有責任確保封裝的字符串不會破壞原有的語義,也不能包含有歧義的聲明或表達式,如"{ foo: bar() }\n['foo']()",這一句既是合法的表達式也是語義完全不同的合法程序。
## type [JSStr](https://github.com/golang/go/blob/master/src/html/template/content.go#L49 "View Source")
```
type JSStr string
```
JSStr用于封裝一個打算嵌入JavaScript表達式中的字符序列,該字符串必須匹配一系列StringCharacters:
```
StringCharacter :: 除了`\`和行終止符的SourceCharacter | EscapeSequence
```
注意不允許換行,JSStr("foo\\nbar")是可以的,但JSStr("foo\\\nbar")不可以。
## type [URL](https://github.com/golang/go/blob/master/src/html/template/content.go#L56 "View Source")
```
type URL string
```
URL用來封裝一個已知安全的URL或URL子字符串(參見[RFC 3986](http://tools.ietf.org/html/rfc3986))
形如`javascript:checkThatFormNotEditedBeforeLeavingPage()`的來源可信的URL應寫進頁面里,但一般動態的`javascript:` URL排除在外(不寫進頁面),因為它們是頻繁使用的注入向量。
## type [CSS](https://github.com/golang/go/blob/master/src/html/template/content.go#L21 "View Source")
```
type CSS string
```
CSS用于包裝匹配如下任一條的已知安全的內容:
```
1\. CSS3樣式表,如`p { color: purple }`
2\. CSS3規則,如`a[href=~"https:"].foo#bar`
3\. CSS3聲明,如`color: red; margin: 2px`
4\. CSS3規則,如`rgba(0, 0, 255, 127)`
```
參見:[http://www.w3.org/TR/css3-syntax/#parsing](http://www.w3.org/TR/css3-syntax/#parsing)?
以及:[https://web.archive.org/web/20090211114933/http://w3.org/TR/css3-syntax#style](https://web.archive.org/web/20090211114933/http:/w3.org/TR/css3-syntax#style)
## type [Template](https://github.com/golang/go/blob/master/src/html/template/template.go#L19 "View Source")
```
type Template struct {
// 底層的模板解析樹,會更新為HTML安全的
Tree *parse.Tree
// 內含隱藏或非導出字段
}
```
Template類型是text/template包的Template類型的特化版本,用于生成安全的HTML文本片段。
### func [Must](https://github.com/golang/go/blob/master/src/html/template/template.go#L294 "View Source")
```
func Must(t *Template, err error) *Template
```
Must函數用于包裝返回(\*Template, error)的函數/方法調用,它會在err非nil時panic,一般用于變量初始化:
```
var t = template.Must(template.New("name").Parse("html"))
```
### func [New](https://github.com/golang/go/blob/master/src/html/template/template.go#L215 "View Source")
```
func New(name string) *Template
```
創建一個名為name的模板。
### func [ParseFiles](https://github.com/golang/go/blob/master/src/html/template/template.go#L305 "View Source")
```
func ParseFiles(filenames ...string) (*Template, error)
```
ParseFiles函數創建一個模板并解析filenames指定的文件里的模板定義。返回的模板的名字是第一個文件的文件名(不含擴展名),內容為解析后的第一個文件的內容。至少要提供一個文件。如果發生錯誤,會停止解析并返回nil。
### func [ParseGlob](https://github.com/golang/go/blob/master/src/html/template/template.go#L358 "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/html/template/template.go#L250 "View Source")
```
func (t *Template) Name() string
```
返回模板t的名字。
### func (\*Template) [Delims](https://github.com/golang/go/blob/master/src/html/template/template.go#L277 "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/html/template/template.go#L267 "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/html/template/template.go#L179 "View Source")
```
func (t *Template) Clone() (*Template, error)
```
Clone方法返回模板的一個副本,包括所有相關聯的模板。模板的底層表示樹并未拷貝,而是拷貝了命名空間,因此拷貝調用Parse方法不會修改原模板的命名空間。Clone方法用于準備模板的公用部分,向拷貝中加入其他關聯模板后再進行使用。
如果t已經執行過了,會返回錯誤。
### func (\*Template) [Lookup](https://github.com/golang/go/blob/master/src/html/template/template.go#L284 "View Source")
```
func (t *Template) Lookup(name string) *Template
```
Lookup方法返回與t關聯的名為name的模板,如果沒有這個模板會返回nil。
### func (\*Template) [Templates](https://github.com/golang/go/blob/master/src/html/template/template.go#L38 "View Source")
```
func (t *Template) Templates() []*Template
```
Templates方法返回與t相關聯的模板的切片,包括t自己。
### func (\*Template) [New](https://github.com/golang/go/blob/master/src/html/template/template.go#L231 "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/html/template/template.go#L151 "View Source")
```
func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)
```
AddParseTree方法使用name和tree創建一個模板并使它和t相關聯。
如果t已經執行過了,會返回錯誤。
### func (\*Template) [Parse](https://github.com/golang/go/blob/master/src/html/template/template.go#L120 "View Source")
```
func (t *Template) Parse(src string) (*Template, error)
```
Parse方法將字符串text解析為模板。嵌套定義的模板會關聯到最頂層的t。Parse可以多次調用,但只有第一次調用可以包含空格、注釋和模板定義之外的文本。如果后面的調用在解析后仍剩余文本會引發錯誤、返回nil且丟棄剩余文本;如果解析得到的模板已有相關聯的同名模板,會覆蓋掉原模板。
### func (\*Template) [ParseFiles](https://github.com/golang/go/blob/master/src/html/template/template.go#L312 "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/html/template/template.go#L367 "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/html/template/template.go#L69 "View Source")
```
func (t *Template) Execute(wr io.Writer, data interface{}) error
```
Execute方法將解析好的模板應用到data上,并將輸出寫入wr。如果執行時出現錯誤,會停止執行,但有可能已經寫入wr部分數據。模板可以安全的并發執行。
### func (\*Template) [ExecuteTemplate](https://github.com/golang/go/blob/master/src/html/template/template.go#L82 "View Source")
```
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error
```
ExecuteTemplate方法類似Execute,但是使用名為name的t關聯的模板產生輸出。
{% endraw %}
- 庫
- 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