package corelib import ( "html/template" "net/http" ) // noRender 是一个自定义模板函数,忽略不渲染传入的内容 func noRender(s string) template.HTML { return template.HTML(s) } func TemplateHandler(w http.ResponseWriter, data any, name string, filenames ...string) { // 创建一个新的基础模板,并将自定义函数注册到模板中 baseTmpl := template.New("base").Funcs(template.FuncMap{ "noRender": noRender, }) // 添加一个简单的内容以确保基础模板不是空的 _, err := baseTmpl.Parse(`{{define "base"}}{{end}}`) if err != nil { Logger.Errorf("Error creating base template: %v", err) http.Error(w, "Error executing template", http.StatusInternalServerError) } // 解析布局模板及其子模板 _, err = baseTmpl.ParseFiles(filenames...) if err != nil { Logger.Errorf("Error parsing templates: %v", err) http.Error(w, "Error executing template", http.StatusInternalServerError) } // 加载所有模板文件 tmpl, err := baseTmpl.Clone() if err != nil { Logger.Errorf("error cloning base template: %v", err) http.Error(w, "Error executing template", http.StatusInternalServerError) } err = tmpl.ExecuteTemplate(w, name, data) if err != nil { Logger.Errorf("Error executing template: %v", err) http.Error(w, "Error executing template", http.StatusInternalServerError) } }