模板“head”插入“index”模板并使用一个变量 {{ .Title }}Main.go:package mainimport ( "html/template" "net/http" "github.com/julienschmidt/httprouter")var ( t = template.Must(template.ParseGlob("templates/*.tpl")))type Page struct { Title string Desc string}func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { index := Page{Title: "This is title", Desc: "Desc"} t.ExecuteTemplate(w, "index", index)}func main() { router := httprouter.New() router.GET("/", Index) http.ListenAndServe(":8080", router)}索引.tpl:{{ define "index" }}<!DOCTYPE html><html> {{ template "head" }}<body> <h1>Main info:</h1> Title: {{ .Title }} Desc: {{ .Desc }}</body></html>{{ end }}头.tpl:{{ define "head" }}<head> <meta charset="UTF-8"> <title>{{ .Title }}</title></head>{{ end }}我得到这个 html:<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title></title></head><body> <h1>Main info:</h1> Title: This is title Desc: Desc</body></html>变量 {{ .Title }} 适用于网站主体,但不适用于头部。
- 1 回答
- 0 关注
- 279 浏览
添加回答
举报
0/150
提交
取消