package gin
import("html/template""path/filepath""strings""os""io/fs""fmt")// LoadHTMLFolder loads HTML files identified by glob pattern// and associates the result with HTML renderer.func(engine *Engine)LoadHTMLFolder(path string){
templ := template.Must(parseHtml(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap),path))
engine.SetHTMLTemplate(templ)}funcparseHtml(t *template.Template, folder string)(*template.Template,error){// 获取模板文件加载
tplFiles :=map[string]string{}
filepath.WalkDir(folder,func(path string, d fs.DirEntry, err error)error{if!d.IsDir()&& strings.HasSuffix(d.Name(),".html"){
name := strings.TrimPrefix(path,folder)
name = strings.TrimPrefix(strings.ReplaceAll(name,"\\","/"),"/")
tplFiles[name]= path
}returnnil})returnparseFiles(t, readFileOS, tplFiles)}// parseFiles is the helper for the method and function. If the argument// template is nil, it is created from the first file.funcparseFiles(t *template.Template, readFile func(string)(string,[]byte,error), filenames map[string]string)(*template.Template,error){iflen(filenames)==0{// Not really a problem, but be consistent.returnnil, fmt.Errorf("html/template: no files named in call to ParseFiles")}// for _, filename := range filenamesfor name, filename :=range filenames {// 默认是 _, b, err := readFile(filename)_, b, err :=readFile(filename)if err !=nil{returnnil, err
}
s :=string(b)// First template becomes return value if not already defined,// and we use that one for subsequent New calls to associate// all the templates together. Also, if this file has the same name// as t, this file becomes the contents of t, so// t, err := New(name).Funcs(xxx).ParseFiles(name)// works. Otherwise we create a new template associated with t.var tmpl *template.Template
if t ==nil{
t = template.New(name)}if name == t.Name(){
tmpl = t
}else{
tmpl = t.New(name)}_, err = tmpl.Parse(s)if err !=nil{returnnil, err
}}return t,nil}funcreadFileOS(file string)(name string, b []byte, err error){
name = filepath.Base(file)
b, err = os.ReadFile(file)return}