Go 是否可以在应用程序启动后重新加载html模板?
现在,我将所有模板解析为一个变量,如下所示:Go 是否可以在应用程序启动后重新加载html模板?,go,Go,现在,我将所有模板解析为一个变量,如下所示: var templates = template.New("Template") func LoadTemplates() { filepath.Walk("view/", func(path string, info os.FileInfo, err error) error { if strings.HasSuffix(path, ".html") { templates.ParseFiles(p
var templates = template.New("Template")
func LoadTemplates() {
filepath.Walk("view/", func(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, ".html") {
templates.ParseFiles(path)
}
return nil
})
}
func Render(w http.ResponseWriter, tmplName string, data interface{}) {
if err := templates.ExecuteTemplate(w, tmplName, data); err != nil {
log.Println(err)
}
}
因此,如果我做了任何更改,我需要重新启动整个应用程序。是否有任何方法可以使更改在进行时得到反映?是的,可以在运行时重新加载(html或文本)模板 只要应用程序可以访问从中读取模板的文件夹,就可以简单地重复模板解析 你可以这样做:
var templates = template.New("Template")
func folderChanged(folder string) bool {
// todo: implement filesystem watcher here
return true
}
func ReloadTemplates(templateFolder string) {
newTemplates, err := LoadTemplates(templateFolder)
if err != nil {
log.Println("Unable to load templates: %s", err)
return
}
// override existing templates variable
templates = newTemplates
}
func LoadTemplates(folder string) (*template.Template, error) {
template := template.New("Template")
walkError := filepath.Walk(folder, func(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, ".html") {
_, parseError := template.ParseFiles(path)
if parseError != nil {
return parseError
}
}
return nil
})
return template, walkError
}
func Render(w http.ResponseWriter, tmplName string, data interface{}) {
templateFolder := "view"
if folderChanged(templateFolder) {
ReloadTemplates(templateFolder)
}
if err := templates.ExecuteTemplate(w, tmplName, data); err != nil {
log.Println(err)
}
}
如果您使用的是一个相对路径,如示例中的
/view
-文件夹,则只有在执行应用程序的目录中有这样一个子文件夹时,它才会起作用。如果不是这样,我建议使用相对于用户主目录的路径或类似的路径。在开发/调试模式下,在每次请求时重新加载模板完全可以
您可以像这样定义一个接口和两个“模板执行器”
包装模板。Execute()。在运行时选择您想要的选项,例如
const templateGlob = "templates/*.html"
const debug = true
var executor TemplateExecutor
func main() {
if debug {
executor = DebugTemplateExecutor{templateGlob}
} else {
executor = ReleaseTemplateExecutor{
template.Must(template.ParseGlob(templateGlob)),
}
}
http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
executor.ExecuteTemplate(w, "test.html", nil)
})
http.ListenAndServe(":3000", nil)
}
如果您需要在生产中进行热重新加载,我建议您查看目录中的更改,而不是在每次请求时编译它。解决了我的问题,不再需要在模板编辑之间重新启动我的应用程序-谢谢!
const templateGlob = "templates/*.html"
const debug = true
var executor TemplateExecutor
func main() {
if debug {
executor = DebugTemplateExecutor{templateGlob}
} else {
executor = ReleaseTemplateExecutor{
template.Must(template.ParseGlob(templateGlob)),
}
}
http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
executor.ExecuteTemplate(w, "test.html", nil)
})
http.ListenAndServe(":3000", nil)
}