block

block是定义模板{{define "name"}} T1 {{end}}和执行{{template "name" pipeline}}缩写,典型的用法是定义一组根模板,然后通过在其中重新定义块模板进行自定义。
如果多页面都有一个共同的样式,可以用block。

{{block "name" pipeline}} T1 {{end}}
定义根模板base.tmpl

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>Go Templates</title>
</head>
<body>
<div>
<!--定义一个根模板-->
    {{block "content" . }}{{end}}
</div>
</body>
</html>

定义index.tmpl

{{template "base.tmpl"}}

{{define "content"}}
    <div>第一个!</div>
    <div>第二个!</div>
{{end}}

main.go

package main

import (
	"fmt"
	"net/http"
	"text/template"
)

func inheritTemplate(w http.ResponseWriter, r *http.Request) {
	tmpl, err := template.ParseGlob("*.tmpl")
	if err != nil {
		fmt.Println(err)
		return
	}
	tmpl.ExecuteTemplate(w, "index.tmpl", nil)
}
func main() {
	http.HandleFunc("/hello", inheritTemplate)
	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		fmt.Println("HTTP server failed,err:", err)
		return
	}
}

编译结果:

posted on 2021-08-02 18:12  飞飞乐园  阅读(53)  评论(0编辑  收藏  举报