github.com/zxysilent/utils@v0.3.1/tmpl.go (about)

     1  package utils
     2  
     3  import (
     4  	"html/template"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  )
     9  
    10  // LoadTmpl 加载指定目录解析为模板 仅限 .html 文件
    11  // eg: views/index.html ,views/subtmpl/subtmpl.html
    12  // tmpl:=LoadTmpl("./views",funcs)
    13  // tmpl.ExecuteTemplate(yourWriter, "index.html", yourData)、tmpl.ExecuteTemplate(yourWriter, "subtmpl/subtmpl.html", yourData)
    14  func LoadTmpl(root string, funcs template.FuncMap) (*template.Template, error) {
    15  	tmpl := template.New("LoadTmpl")
    16  	if funcs != nil {
    17  		tmpl.Funcs(funcs)
    18  	}
    19  	rln := len(root)
    20  	err := filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
    21  		if err != nil {
    22  			return err
    23  		}
    24  		pln := len(path)
    25  		// 是文件 并且是 .html 结尾
    26  		if !fi.IsDir() && pln > 4 && path[pln-5:] == ".html" {
    27  			buf, err := os.ReadFile(path)
    28  			if err != nil {
    29  				return err
    30  			}
    31  			name := strings.ReplaceAll(path, "\\", "/")
    32  			_, err = tmpl.New(name[rln-1:]).Parse(string(buf))
    33  			if err != nil {
    34  				return err
    35  			}
    36  		}
    37  		return nil
    38  	})
    39  	return tmpl, err
    40  }