上面的代码※是匹配符*,※※表示任意层级的子文件夹,※表示单层或任意字符
//template\test1\block.tmpl
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{template "js.html"}}
<title>Documenttitle>
head>
<body>
<div>part1div>
{{template "part0"}}
<div>part2div>
{{block "part0" .}}{{end}}
<div>part3div>
body>
html>
//template\test1\useblock.tmpl
{{template "block.tmpl"}}
{{define "part0"}}
<h1>this is part0 h1>
{{end}}
//template\test2\js.html
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous">script>
//a1.go
package main
import (
"html/template"
"log"
"net/http"
// "github.com/gin-gonic/gin"
)
func main() {
http.HandleFunc("/a1", a1)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Println("HTTP server failed,err:", err)
return
}
}
func a1(w http.ResponseWriter, r *http.Request) {
tmpl,err:=template.ParseGlob("./template/**/*.*")
// tmpl,err:=template.ParseGlob("./template/test*/*")
// tmpl,err:=template.ParseGlob("./template/*/*/*")
// tmpl,err:=template.ParseGlob("./template/**/*.tmpl")
if err != nil {
log.Println("create template failed, err1:", err)
return
}
err=tmpl.ExecuteTemplate(w,"useblock.tmpl",nil)
if err != nil {
log.Println("create template failed, err2:", err)
return
}
}
访问a1页面,内容如下
part1
this is part0
part2
this is part0
part3
遇到的bug:
为了测试建了test2文件夹,一读取就报错The handle is invalid。删除后重新建一个就没bug了,原因不明。
重命名模板名
//template\test1\block.tmpl
{{define "a/b/c.html"}}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{template "js.html"}}
<title>Documenttitle>
head>
<body>
<div>part1div>
{{template "part0"}}
<div>part2div>
{{block "part0" .}}{{end}}
<div>part3div>
body>
html>
{{end}}
//template\test1\useblock.tmpl
{{template "a/b/c.html"}}
{{define "part0"}}
<h1>this is part0 h1>
{{end}}