创建模板文件
1、创建layouts文件夹 2、在layouts文件夹中创建以下三个模板文件 header.html sidebar.html footer.html 3、创建template_admin.html模板文件 4、使用{{define "template_name"}}定义模板 5、使用{{template "template_name" .}}引入模板文件,注意标签后面的点"."一定要带上,在引入的模板中解析变量 6、变量输出{{.name}}
header.html模板文件中添加
{{define "layouts/header"}} <header> header </header> {{end}}
sidebar.html模板文件中添加
{{define "layouts/sidebar"}} <nav> sidebar </nav> {{end}}
footer.html模板文件中添加
{{define "layouts/footer"}} <footer> footer </footer> {{end}}
template_admin.html模板文件中添加
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{.title}}</title> </head> <body> <!-- include header --> {{template "layouts/header" .}} <!-- include sidebar --> {{template "layouts/sidebar" .}} <!-- include content --> {{template "content" .}} <!-- include footer --> {{template "layouts/footer" .}} </body> </html>
创建content.html与content-1.html模板文件,模板中添加
{{define "content"}} <div> {{.content}} </div> {{end}}
创建main.go文件,添加
type Content map[string]interface{} func main() { LayoutTpl() } func LayoutTpl() { http.HandleFunc("/content", func(w http.ResponseWriter, r *http.Request) { t, err := setAdminContentFile("content.html") if err != nil { fmt.Println("parse file err:", err.Error()) return } p := Content{"title": "admin", "content": "layouts - template - content"} _ = t.Execute(w, p) }) http.HandleFunc("/content-1", func(w http.ResponseWriter, r *http.Request) { t, err := setAdminContentFile("content-1.html") if err != nil { fmt.Println("parse file err:", err.Error()) return } p := Content{"title": "admin", "content": "layouts - template - content-1"} _ = t.Execute(w, p) }) _ = http.ListenAndServe("127.0.0.1:9080", nil) } func setAdminContentFile(contentFileName string) (*template.Template, error) { files := []string{"template_admin.html", "layouts/header.html", "layouts/sidebar.html", contentFileName, "layouts/footer.html"} return template.ParseFiles(files...) }
终端执行:go run main.go
浏览器访问: http://127.0.0.1:9080/content 如下

content.html
浏览器访问: http://127.0.0.1:9080/content-1 如下

content-1.html
有疑问加站长微信联系(非本文作者)
