下面由golang教程栏目给大家介绍Go语言中使用模板引擎,希望对需要的朋友有所帮助!

1 概述
处理响应主体时,最常见的方式就是发送处理好的 HTML 代码,由于需要将数据嵌入到 HTML 中,那么模板引擎(template engine)就是最好的选择。
html/template
main.go
package mainimport (
"html/template"
"log"
"net/http")func main() {
// 设置 处理函数
http.HandleFunc("/", TestAction)
开启监听(监听浏览器请求)
log.Fatal(http.ListenAndServe(":8084", nil))}func TestAction(w http.ResponseWriter, r *http.Request) {
// 解析模板
t, _ := template.ParseFiles("template/index.html")
// 设置模板数据
data := map[string]interface{}{
"User": "小韩说课",
"List": []string{"Go", "Python", "PHP", "JavaScript"},
}
// 渲染模板,发送响应
t.Execute(w, data)}
template/index.html
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<title>小韩说课</title></head><body>Hello, {{ .User }}<br>你熟悉的技术:<ul>{{ range .List }} <li>{{.}}</li>{{end}}</ul></body></html>执行结果:

以上代码就完了模板引擎的基本使用,包括解析模板,渲染数据,响应结果操作。接下来详细说明。
2 解析模板
template.ParseFiles(filenames ...string) (*Template, error)template.New("name").Parse(src string)3 应用数据并发送响应
func (t *Template) Execute(wr io.Writer, data interface{}) errormap[string]interface{}.User.List完!