3 回答
TA贡献1785条经验 获得超8个赞
如果在模板文件夹中定义所有模板,则可以使用以下命令轻松解析整个目录:
template.Must(template.ParseGlob("YOURDIRECTORY/*"))
例如:
头文件
{{define "header"}}
<head>
<title>Index</title>
</head>
{{end}}
索引.html
{{define "indexPage"}}
<html>
{{template "header"}}
<body>
<h1>Index</h1>
</body>
</html>
{{end}}
main.go
package main
import(
"html/template"
)
// compile all templates and cache them
var templates = template.Must(template.ParseGlob("YOURTEMPLATEDIR/*"))
func main(){
...
}
func IndexHandler(w http.ResponseWriter, r *http.Request) {
// you access the cached templates with the defined name, not the filename
err := templates.ExecuteTemplate(w, "indexPage", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
你执行你的 indexPage-Template templates.ExecuteTemplate(w, "indexPage", nil)
TA贡献2003条经验 获得超2个赞
如果你想用特定文件解析多个目录,这里有一个代码片段:
//parse a pattern in a specific directory
allTemplates := template.Must(template.ParseGlob("Directory/*"))
//add another directory for parsing
allTemplates = template.Must(allTemplates.ParseGlob("Another_Directory/*.tmpl"))
//add specific file name
allTemplates = template.Must(allTemplates.ParseFiles("path/to/file.tmpl"))
func main() {
...
}
func FileHandler(w http.ResponseWriter, r *http.Request) {
// access cached template by file name (in case you didn't define its name)
err := allTemplates.ExecuteTemplate(w, "file.tmpl", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func NameHandler(w http.ResponseWriter, r *http.Request) {
// access cached template by handler name
err := allTemplates.ExecuteTemplate(w, "handlerName", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
快捷方式:
allTemplates := template.Must(
template.Must(
template.Must(
template.ParseGlob("directory/*.tmpl")).
ParseGlob("another_directory/*.tmpl")).
ParseFiles("path/to/file.tmpl")),
)
file.tmpl 可以如下所示:
<html>
This is a template file
</html>
name.tmpl 应该看起来像这样
{{define "handlerName" }}
<p>this is a handler</p>
{{end}}
- 3 回答
- 0 关注
- 183 浏览
添加回答
举报