github.com/sandwich-go/boost@v1.3.29/misc/xtemplate/xtemplate.go (about) 1 package xtemplate 2 3 import ( 4 "bytes" 5 "github.com/Masterminds/sprig" 6 "github.com/sandwich-go/boost/misc/goformat" 7 "github.com/sandwich-go/boost/xos" 8 "github.com/sandwich-go/boost/xstrings" 9 "html/template" 10 "path/filepath" 11 ) 12 13 var funcMap = template.FuncMap{ 14 "Unescaped": func(str string) template.HTML { return template.HTML(str) }, 15 "CamelCase": xstrings.CamelCase, 16 "SnakeCase": xstrings.SnakeCase, 17 "FirstLower": xstrings.FirstLower, 18 "FirstUpper": xstrings.FirstUpper, 19 } 20 21 func init() { 22 for k, v := range funcMap { 23 funcMap[xstrings.FirstLower(k)] = v 24 } 25 } 26 27 // Execute 根据指定的 template 以及 args 生成对应文本内容 28 func Execute(templateStr string, args interface{}, opts ...Option) ([]byte, error) { 29 cfg := NewOptions(opts...) 30 t, err := template.New(cfg.GetName()). 31 Funcs(funcMap). 32 Funcs(sprig.FuncMap()). 33 Parse(templateStr) 34 if err != nil { 35 return nil, err 36 } 37 buf := bytes.NewBuffer(nil) 38 err = t.Execute(buf, args) 39 if err != nil { 40 return nil, err 41 } 42 bytesUsing := buf.Bytes() 43 for _, filter := range cfg.GetFilers() { 44 if filter == nil { 45 continue 46 } 47 bytesUsing = filter(bytesUsing) 48 } 49 if len(cfg.GetFileName()) > 0 { 50 if filepath.Ext(cfg.GetFileName()) == ".go" { 51 bytesUsing, err = goformat.ProcessCode(bytesUsing) 52 if err != nil { 53 return nil, err 54 } 55 } 56 err = xos.FilePutContents(cfg.GetFileName(), bytesUsing) 57 if err != nil { 58 return nil, err 59 } 60 } 61 return bytesUsing, nil 62 }