github.com/llimllib/devd@v0.0.0-20230426145215-4d29fc25f909/ricetemp/ricetemp.go (about) 1 // Package ricetemp makes templates from a ricebox. 2 package ricetemp 3 4 import ( 5 "html/template" 6 "os" 7 "strings" 8 9 "github.com/GeertJohan/go.rice" 10 "github.com/dustin/go-humanize" 11 ) 12 13 func bytes(size int64) string { 14 return humanize.Bytes(uint64(size)) 15 } 16 17 func fileType(f os.FileInfo) string { 18 if f.IsDir() { 19 return "dir" 20 } 21 if strings.HasPrefix(f.Name(), ".") { 22 return "hidden" 23 } 24 return "file" 25 } 26 27 // MustMakeTemplates makes templates, and panic on error 28 func MustMakeTemplates(rb *rice.Box) *template.Template { 29 templates, err := MakeTemplates(rb) 30 if err != nil { 31 panic(err) 32 } 33 return templates 34 } 35 36 // MakeTemplates takes a rice.Box and returns a html.Template 37 func MakeTemplates(rb *rice.Box) (*template.Template, error) { 38 tmpl := template.New("") 39 40 funcMap := template.FuncMap{ 41 "bytes": bytes, 42 "reltime": humanize.Time, 43 "fileType": fileType, 44 } 45 tmpl.Funcs(funcMap) 46 47 err := rb.Walk("", func(path string, info os.FileInfo, err error) error { 48 if !info.IsDir() { 49 _, err := tmpl.New(path).Parse(rb.MustString(path)) 50 if err != nil { 51 return err 52 } 53 } 54 return nil 55 }) 56 return tmpl, err 57 }