湖上湖
如果你想用特定文件解析多个目录,这里有一个代码片段://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}}