html/template
模板
Printf也可以做到输出格式化,当然,对于简单的例子来说足够了,但是我们有时候还是需要复杂的输出格式,甚至需要将格式化代码分离开来。这时,可以使用text/template和html/template。
两个模板库: text/template 和 html/template 。这两个库类似,当需要输出html格式的代码时需要使用html/template。
模板文件
index.html 文件
<!DOCTYPE html>
<html lang=en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{.}} //此处为待定值
</body>
</html>
main.go 文件
func hh (w http.ResponseWriter,r *http.Request) {
//解析tmpl中的内容
t, err1 := template.ParseFiles("./test04/index.html")
if err1 != nil {
fmt.Println("err1 = ",err1)
return
}
//赋值给tmpl中的待定值 将data赋给w
err := t.Execute(w,"hahahahahahahaha")
if err != nil {
fmt.Println("err = ",err)
return
}
}
func main() {
http.HandleFunc("/",hh)
//启动web服务
http.ListenAndServe(":8000",nil)
}
运行程序,在浏览器打开:http://localhost:8080/ 我们可以看到浏览器页面显示 hahahahahahahaha
!即使模板文件这时有修改,刷新浏览器后页面也即更新,这个过程并不需要重启web服务。