## 使用 text/template和HTML/templates包
Go為模板操作提供了豐富的支持。嵌套模板,導入函數,表示變量,迭代數據等等都很簡單。如果需要比CSV數據格式更復雜的東西,模板可能是一個不錯的解決方案。
模板的另一個應用是網站的頁面渲染。當我們想要將服務器端數據呈現給客戶端時,模板可以很好地滿足要求。起初,Go模板可能會讓人感到困惑。 本章將探討如何使用模板。
### 實踐
1. 建立templates.go:
```
package templates
import (
"os"
"strings"
"text/template"
)
const sampleTemplate = `
This template demonstrates printing a {{ .Variable | printf "%#v" }}.
{{if .Condition}}
If condition is set, we'll print this
{{else}}
Otherwise, we'll print this instead
{{end}}
Next we'll iterate over an array of strings:
{{range $index, $item := .Items}}
{{$index}}: {{$item}}
{{end}}
We can also easily import other functions like strings.Split
then immediately used the array created as a result:
{{ range $index, $item := split .Words ","}}
{{$index}}: {{$item}}
{{end}}
Blocks are a way to embed templates into one another
{{ block "block_example" .}}
No Block defined!
{{end}}
{{/*
This is a way
to insert a multi-line comment
*/}}
`
const secondTemplate = `
{{ define "block_example" }}
{{.OtherVariable}}
{{end}}
`
// RunTemplate初始化模板并展示了對模板的基本操作
func RunTemplate() error {
data := struct {
Condition bool
Variable string
Items []string
Words string
OtherVariable string
}{
Condition: true,
Variable: "variable",
Items: []string{"item1", "item2", "item3"},
Words: "another_item1,another_item2,another_item3",
OtherVariable: "I'm defined in a second template!",
}
funcmap := template.FuncMap{
"split": strings.Split,
}
// 這里可以鏈式調用
t := template.New("example")
t = t.Funcs(funcmap)
// 我們可以使用Must來替代它
// template.Must(t.Parse(sampleTemplate))
t, err := t.Parse(sampleTemplate)
if err != nil {
return err
}
// 為了模擬長時間操作我們通過克隆創建另一個模板 然后解析它
t2, err := t.Clone()
if err != nil {
return err
}
t2, err = t2.Parse(secondTemplate)
if err != nil {
return err
}
// 將數據填充后的模板寫入標準輸出
err = t2.Execute(os.Stdout, &data)
if err != nil {
return err
}
return nil
}
```
2. 建立template_files.go:
```
package templates
import (
"io/ioutil"
"os"
"path/filepath"
"text/template"
)
//CreateTemplate會創建一個包含數據的模板文件
func CreateTemplate(path string, data string) error {
return ioutil.WriteFile(path, []byte(data), os.FileMode(0755))
}
// InitTemplates在文件夾中設置一系列的模板文件
func InitTemplates() error {
tempdir, err := ioutil.TempDir("", "temp")
if err != nil {
return err
}
// 在操作完成后全部都將被刪除
defer os.RemoveAll(tempdir)
err = CreateTemplate(filepath.Join(tempdir, "t1.tmpl"), `
Template 1! {{ .Var1 }}
{{ block "template2" .}} {{end}}
{{ block "template3" .}} {{end}}
`)
if err != nil {
return err
}
err = CreateTemplate(filepath.Join(tempdir, "t2.tmpl"), `
{{ define "template2"}}Template 2! {{ .Var2 }}{{end}}
`)
if err != nil {
return err
}
err = CreateTemplate(filepath.Join(tempdir, "t3.tmpl"), `
{{ define "template3"}}Template 3! {{ .Var3 }}{{end}}
`)
if err != nil {
return err
}
pattern := filepath.Join(tempdir, "*.tmpl")
// 組合所有匹配glob的文件并將它們組合成一個模板
tmpl, err := template.ParseGlob(pattern)
if err != nil {
return err
}
// Execute函數可以運用于map和struct
tmpl.Execute(os.Stdout, map[string]string{
"Var1": "Var1!!",
"Var2": "Var2!!",
"Var3": "Var3!!",
})
return nil
}
```
3. 建立 html_templates.go:
```
package templates
import (
"fmt"
"html/template"
"os"
)
// HTMLDifferences 展示了html/template 和 text/template的一些不同
func HTMLDifferences() error {
t := template.New("html")
t, err := t.Parse("<h1>Hello! {{.Name}}</h1>\n")
if err != nil {
return err
}
// html/template自動轉義不安全的操作,比如javascript注入
// 這會根據變量的位置不同而呈現不完全相同的結果
err = t.Execute(os.Stdout, map[string]string{"Name": "<script>alert('Can you see me?')</script>"})
if err != nil {
return err
}
// 你也可以手動調用轉義器
fmt.Println(template.JSEscaper(`example <example@example.com>`))
fmt.Println(template.HTMLEscaper(`example <example@example.com>`))
fmt.Println(template.URLQueryEscaper(`example <example@example.com>`))
return nil
}
```
4. 以上示例打印顯示較長,大家可自行運行查看。
### 說明
Go有兩個模板包 - text/template和html/template。這兩個包的部分函數看起來非常相似,實際功能也確實如此。通常,使用html/template來呈現網站。模板是純文本,但變量和函數可以在大括號塊內使用。
模板包還提供了處理文件的便捷方法。示例在臨時目錄中創建了許多模板,然后使用一行代碼讀取所有模板。
html/template包是對text/template包的包裝。所有模板示例都對html/template包同樣適用,除了import語句無需其他任何修改。HTML模板提供了上下文感知安全性的額外好處。這可以防止諸如JavaScript注入之類的事情。
模板包能夠滿足你對頁面操作的期望。在向HTML和JavaScript發布結果時,你可以輕松組合模板,添加應用程序邏輯并確保安全性。
* * * *
學識淺薄,錯誤在所難免。歡迎在群中就本書提出修改意見,以饗后來者,長風拜謝。
Golang中國(211938256)
beego實戰(258969317)
Go實踐(386056972)
- 前言
- 第一章 I/O和文件系統
- 常見 I/O 接口
- 使用bytes和strings包
- 操作文件夾和文件
- 使用CSV格式化數據
- 操作臨時文件
- 使用 text/template和HTML/templates包
- 第二章 命令行工具
- 解析命令行flag標識
- 解析命令行參數
- 讀取和設置環境變量
- 操作TOML,YAML和JSON配置文件
- 操做Unix系統下的pipe管道
- 處理信號量
- ANSI命令行著色
- 第三章 數據類型轉換和解析
- 數據類型和接口轉換
- 使用math包和math/big包處理數字類型
- 貨幣轉換和float64注意事項
- 使用指針和SQL Null類型進行編碼和解碼
- 對Go數據編碼和解碼
- Go中的結構體標簽和反射
- 通過閉包實現集合操作
- 第四章 錯誤處理
- 錯誤接口
- 使用第三方errors包
- 使用log包記錄錯誤
- 結構化日志記錄
- 使用context包進行日志記錄
- 使用包級全局變量
- 處理恐慌
- 第五章 數據存儲
- 使用database/sql包操作MySQL
- 執行數據庫事務接口
- SQL的連接池速率限制和超時
- 操作Redis
- 操作MongoDB
- 創建存儲接口以實現數據可移植性
- 第六章 Web客戶端和APIs
- 使用http.Client
- 調用REST API
- 并發操作客戶端請求
- 使用OAuth2
- 實現OAuth2令牌存儲接口
- 封裝http請求客戶端
- 理解GRPC的使用
- 第七章 網絡服務
- 處理Web請求
- 使用閉包進行狀態處理
- 請求參數驗證
- 內容渲染
- 使用中間件
- 構建反向代理
- 將GRPC導出為JSON API
- 第八章 測試
- 使用標準庫進行模擬
- 使用Mockgen包
- 使用表驅動測試
- 使用第三方測試工具
- 模糊測試
- 行為驅動測試
- 第九章 并發和并行
- 第十章 分布式系統
- 第十一章 響應式編程和數據流
- 第十二章 無服務器編程
- 第十三章 性能改進