ファイルを解析するために、template.ParseFiles の変数を設定しました。現在、各ファイルを手動で設定する必要があります。
2つのこと:
各ファイルを個別に手動で追加する必要がないように、メイン フォルダーと多数のサブフォルダーを調べて自動的に ParseFiles に追加するにはどうすればよいでしょうか?
現在、ParseFiles に同じ名前のファイルを追加すると実行時にエラーが発生するため、サブフォルダーで同じ名前のファイルを呼び出すにはどうすればよいでしょうか。
var templates = template.Must(template.ParseFiles(
"index.html", // main file
"subfolder/index.html" // subfolder with same filename errors on runtime
"includes/header.html", "includes/footer.html",
))
func main() {
// Walk and ParseFiles
filepath.Walk("files", func(path string, info os.FileInfo, err error) {
if !info.IsDir() {
// Add path to ParseFiles
}
return
})
http.HandleFunc("/", home)
http.ListenAndServe(":8080", nil)
}
func home(w http.ResponseWriter, r *http.Request) {
render(w, "index.html")
}
func render(w http.ResponseWriter, tmpl string) {
err := templates.ExecuteTemplate(w, tmpl, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}