github.com/bketelsen/buffalo@v0.9.5/render/template_helpers.go (about) 1 package render 2 3 import ( 4 "encoding/json" 5 "html/template" 6 "path/filepath" 7 "sync" 8 9 "github.com/gobuffalo/tags" 10 "github.com/pkg/errors" 11 ) 12 13 var assetsMutex = &sync.Mutex{} 14 var assetMap map[string]string 15 16 func loadManifest(manifest string) error { 17 assetsMutex.Lock() 18 defer assetsMutex.Unlock() 19 20 err := json.Unmarshal([]byte(manifest), &assetMap) 21 return err 22 } 23 24 func assetPathFor(file string) string { 25 assetsMutex.Lock() 26 defer assetsMutex.Unlock() 27 28 filePath := assetMap[file] 29 if filePath == "" { 30 filePath = file 31 } 32 33 return filepath.Join("/assets", filePath) 34 } 35 36 func (s templateRenderer) addAssetsHelpers(helpers Helpers) Helpers { 37 helpers["assetPath"] = func(file string) (string, error) { 38 return s.assetPath(file) 39 } 40 41 helpers["javascriptTag"] = func(file string, options tags.Options) (template.HTML, error) { 42 h, err := s.assetPath(file) 43 if err != nil { 44 return "", errors.WithStack(err) 45 } 46 return jsTag(h, options), nil 47 } 48 49 helpers["stylesheetTag"] = func(file string, options tags.Options) (template.HTML, error) { 50 h, err := s.assetPath(file) 51 if err != nil { 52 return "", errors.WithStack(err) 53 } 54 return cssTag(h, options), nil 55 } 56 57 return helpers 58 } 59 60 func jsTag(src string, options tags.Options) template.HTML { 61 62 if options == nil { 63 options = tags.Options{} 64 } 65 66 if options["type"] == nil { 67 options["type"] = "text/javascript" 68 } 69 70 options["src"] = src 71 jsTag := tags.New("script", options) 72 73 return jsTag.HTML() 74 } 75 76 func cssTag(href string, options tags.Options) template.HTML { 77 if options == nil { 78 options = tags.Options{} 79 } 80 81 if options["rel"] == nil { 82 options["rel"] = "stylesheet" 83 } 84 85 if options["media"] == nil { 86 options["media"] = "screen" 87 } 88 89 options["href"] = href 90 cssTag := tags.New("link", options) 91 92 return cssTag.HTML() 93 }