下面由golang教程欄目給大家介紹Go語言中使用模板引擎,希望對需要的朋友有所幫助!
1 概述
處理響應(yīng)主體時,最常見的方式就是發(fā)送處理好的 HTML 代碼,由于需要將數(shù)據(jù)嵌入到 HTML 中,那么模板引擎(template engine)就是最好的選擇。
Go語言中,提供了 html/template
包,實現(xiàn)模板引擎的相關(guān)功能??焖偈褂檬纠?/p>
main.go
package mainimport ( "html/template" "log" "net/http")func main() { // 設(shè)置 處理函數(shù) http.HandleFunc("/", TestAction) 開啟監(jiān)聽(監(jiān)聽瀏覽器請求) log.Fatal(http.ListenAndServe(":8084", nil))}func TestAction(w http.ResponseWriter, r *http.Request) { // 解析模板 t, _ := template.ParseFiles("template/index.html") // 設(shè)置模板數(shù)據(jù) data := map[string]interface{}{ "User": "小韓說課", "List": []string{"Go", "Python", "PHP", "JavaScript"}, } // 渲染模板,發(fā)送響應(yīng) t.Execute(w, data)}
template/index.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>小韓說課</title></head><body>Hello, {{ .User }}<br>你熟悉的技術(shù):<ul>{{ range .List }} <li>{{.}}</li>{{end}}</ul></body></html>
執(zhí)行結(jié)果:
以上代碼就完了模板引擎的基本使用,包括解析模板,渲染數(shù)據(jù),響應(yīng)結(jié)果操作。接下來詳細(xì)說明。
2 解析模板
函數(shù) template.ParseFiles(filenames ...string) (*Template, error)
可以解析模板文件,并得到模板對象。參數(shù)為模板文件。同時會以模板文件的文件名(不包含后綴名)作為模板的名字。
還可以使用 template.New("name").Parse(src string)
來創(chuàng)建模板對象,并完成解析模板內(nèi)容。
3 應(yīng)用數(shù)據(jù)并發(fā)送響應(yīng)
函數(shù) func (t *Template) Execute(wr io.Writer, data interface{}) error
將 data 應(yīng)用到解析好的模板上,并將輸出寫入 wr。如果執(zhí)行時出現(xiàn)錯誤,會停止執(zhí)行,但有可能已經(jīng)寫入wr部分?jǐn)?shù)據(jù)。
data 數(shù)據(jù)可以接受任意類型,最常見的類型為:map[string]interface{}
,通過不同的下標(biāo)來區(qū)分部分的分配數(shù)據(jù)。在模板中使用 .User
,.List
來訪問分配數(shù)據(jù)中的 User 和 List。
完!