定义模板
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>tmpl test</title>
</head>
<body>
<h1>测试嵌套tempalte语法</h1>
<hr>
{{/*嵌套了另外一个单独的模板文件*/}}
{{template "ul.tmpl"}}
<hr>
{{/*嵌套了另外一个define定义的模板*/}}
{{template "ol.tmpl"}}
<div>hello,{{ . }}</div>
</body>
</html>
{{/*通过define定义一个模板*/}}
{{define "ol.tmpl"}}
<ol>
<li>吃饭</li>
<li>睡觉</li>
<li>打豆豆</li>
</ol>
{{end}}
ul.tmpl文件
<ul>
<li>注释</li>
<li>日志</li>
<li>测试</li>
</ul>
解析模板&渲染模板
func demo1(w http.ResponseWriter,r *http.Request) {
//文件顺序顺序不能错
t, err := template.ParseFiles("./t.tmpl","./ul.tmpl")
if err != nil {
fmt.Printf("parse template failed err : %v\n",err)
return
}
name := "小王子"
t.Execute(w,name)
}
main函数
func main() {
http.HandleFunc("/templDemo",demo1)
err := http.ListenAndServe(":9090", nil)
if err != nil {
fmt.Printf("HTTP server start failed,err : %v", err)
return
}
}