文章目錄
- golang常用庫之-標準庫text/template
- 背景
- 什么是text/template
- text/template庫的使用
golang常用庫之-標準庫text/template
背景
在許多編程場景中,我們經常需要把數據按照某種格式進行輸出,比如生成HTML頁面,或者生成配置文件。這時,我們就需要模板引擎的幫助。幸運的是,Go語言在標準庫中就提供了兩個強大的模板引擎:text/template和html/template。
什么是text/template
text/template
是Go語言標準庫中的一個強大工具,用于生成文本輸出。它允許你定義模板,然后將數據填充到模板中,非常適合生成報告、配置文件、HTML等。
text/template庫的使用
text/template庫用于生成任何基于文本的格式。它使用雙大括號{{和}}來定義模板的動態部分。讓我們通過一個簡單的例子來看一下它的使用方法。
- 簡單的字符串插值
package mainimport ("os""text/template"
)func main() {// 定義模板tmpl := template.Must(template.New("test").Parse("你好,{{.Name}}!今天是{{.Date}}。\n"))// 準備數據data := struct {Name stringDate string}{Name: "張三",Date: "2025年5月1日",}// 執行模板并輸出到標準輸出err := tmpl.Execute(os.Stdout, data)if err != nil {panic(err)}
}
或
package mainimport ("os""text/template"
)func main() {// 顯式創建template.Template對象var tmpl *template.Templatetmpl = template.New("hello")// 解析模板內容tmpl, err := tmpl.Parse("你好,{{.Name}}!今天是{{.Date}}。\n")if err != nil {panic(err)}// 準備數據data := struct {Name stringDate string}{Name: "張三",Date: "2025年5月2日",}// 執行模板err = tmpl.Execute(os.Stdout, data)if err != nil {panic(err)}
}
- 使用循環(range)
package mainimport ("os""text/template"
)func main() {// 定義模板const templateText = `
我的購物清單:
{{range .Items}}
- {{.}}
{{end}}總計: {{.Count}}項
`tmpl := template.Must(template.New("list").Parse(templateText))// 準備數據data := struct {Items []stringCount int}{Items: []string{"蘋果", "香蕉", "橙子", "牛奶"},Count: 4,}// 執行模板err := tmpl.Execute(os.Stdout, data)if err != nil {panic(err)}
}
- 條件語句(if-else)
package mainimport ("os""text/template"
)func main() {// 定義模板const templateText = `
{{if .Success}}
? 操作成功: {{.Message}}
{{else}}
? 操作失敗: {{.Message}}
{{end}}狀態碼: {{.Code}}
`tmpl := template.Must(template.New("status").Parse(templateText))// 準備數據 - 成功案例success := struct {Success boolMessage stringCode int}{Success: true,Message: "數據已保存",Code: 200,}// 執行模板tmpl.Execute(os.Stdout, success)// 失敗案例failure := struct {Success boolMessage stringCode int}{Success: false,Message: "服務器錯誤",Code: 500,}tmpl.Execute(os.Stdout, failure)
}
- 自定義函數
package mainimport ("os""strings""text/template""time"
)func main() {// 創建模板并添加自定義函數funcMap := template.FuncMap{"upper": strings.ToUpper,"formatDate": func(t time.Time) string {return t.Format("2006年01月02日")},}tmpl := template.New("funcs")tmpl.Funcs(funcMap)// 解析模板tmpl, err := tmpl.Parse(`
用戶: {{.Name | upper}}
注冊時間: {{.RegisterDate | formatDate}}
`)if err != nil {panic(err)}// 準備數據data := struct {Name stringRegisterDate time.Time}{Name: "李四",RegisterDate: time.Date(2024, 3, 15, 0, 0, 0, 0, time.UTC),}// 執行模板err = tmpl.Execute(os.Stdout, data)if err != nil {panic(err)}
}