github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/easy/template.go (about)

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