github.com/jxskiss/gopkg@v0.17.3/easy/template.go (about) 1 package easy 2 3 import ( 4 "io/ioutil" 5 "os" 6 "path/filepath" 7 "regexp" 8 9 htmltemplate "html/template" 10 texttemplate "text/template" 11 ) 12 13 // ParseHTMLTemplates parses files under `rootDir` which matches the regular 14 // expression `rePattern`. Optionally a `funcMap` can be specified to use 15 // with the parsed templates. 16 // 17 // The returned Template holds the parsed templates under the root directory, 18 // template can be retrieved using Template.Lookup(name), where name is the 19 // file path relative to rootDir, without leading "./". 20 func ParseHTMLTemplates(rootDir string, rePattern string, funcMap htmltemplate.FuncMap) (*htmltemplate.Template, error) { 21 t := htmltemplate.New("").Funcs(funcMap) 22 err := parseTemplates(rootDir, rePattern, func(name string, text []byte) error { 23 _, e1 := t.New(name).Parse(string(text)) 24 return e1 25 }) 26 if err != nil { 27 return nil, err 28 } 29 return t, nil 30 } 31 32 // ParseTextTemplates parses files under `rootDir` which matches the regular 33 // expression `rePattern`. Optionally a `funcMap` can be specified to use 34 // with the parsed templates. 35 // 36 // The returned Template holds the parsed templates under the root directory, 37 // template can be retrieved using Template.Lookup(name), where name is the 38 // file path relative to rootDir, without leading "./". 39 func ParseTextTemplates(rootDir string, rePattern string, funcMap texttemplate.FuncMap) (*texttemplate.Template, error) { 40 t := texttemplate.New("").Funcs(funcMap) 41 err := parseTemplates(rootDir, rePattern, func(name string, text []byte) error { 42 _, e1 := t.New(name).Parse(string(text)) 43 return e1 44 }) 45 if err != nil { 46 return nil, err 47 } 48 return t, nil 49 } 50 51 // https://stackoverflow.com/a/50581032 52 func parseTemplates(rootDir string, rePattern string, add func(name string, text []byte) error) error { 53 cleanRoot := filepath.Clean(rootDir) 54 pfx := len(cleanRoot) + 1 55 re, err := regexp.Compile(rePattern) 56 if err != nil { 57 return err 58 } 59 return filepath.Walk(cleanRoot, func(path string, info os.FileInfo, e1 error) error { 60 if e1 != nil { 61 return e1 62 } 63 if info.IsDir() { 64 return nil 65 } 66 name := path[pfx:] 67 if !re.MatchString(name) { 68 return nil 69 } 70 text, e2 := ioutil.ReadFile(path) 71 if e2 != nil { 72 return e2 73 } 74 e2 = add(name, text) 75 return e2 76 }) 77 }