我正在尝试使用在文件夹中行走来动态解析文件,并且我希望能够设置文件“path/file.html”的路径。但我的问题是,如果我在文件夹“path/folder/files.html”中有一个文件,我不能这样做,因为当我 ExecuteTemplate
时,文件名将是相同的“files.html” .是否可以将每个模板命名为 I ParseFiles?
如果尝试一次完成所有文件行不通,我可以一次处理一个文件。
// Parse file and send to responsewriter
func View(w http.ResponseWriter, path string) {
temp, err := template.ParseFiles("application/views/"+path+".html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
temp.ExecuteTemplate(w, path, nil)
}
}
最佳答案
使用 filepath.Walk
和 consumer
方法遍历文件系统,该方法将创建以完整文件路径作为名称的模板:
package main
import (
"fmt"
"html/template"
"os"
"path/filepath"
)
func consumer(p string, i os.FileInfo, e error) error {
t := template.New(p)
fmt.Println(t.Name())
return nil
}
func main() {
filepath.Walk("/path/to/template/root", filepath.WalkFunc(consumer))
}
关于go - 指定已解析模板的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12430870/