github.com/jacobsoderblom/buffalo@v0.11.0/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  	return filepath.ToSlash(filepath.Join("/assets", filePath))
    33  }
    34  
    35  type helperTag struct {
    36  	name string
    37  	fn   func(string, tags.Options) template.HTML
    38  }
    39  
    40  func (s templateRenderer) addAssetsHelpers(helpers Helpers) Helpers {
    41  	helpers["assetPath"] = func(file string) (string, error) {
    42  		return s.assetPath(file)
    43  	}
    44  
    45  	ah := []helperTag{
    46  		{"javascriptTag", jsTag},
    47  		{"stylesheetTag", cssTag},
    48  		{"imgTag", imgTag},
    49  	}
    50  
    51  	for _, h := range ah {
    52  		func(h helperTag) {
    53  			helpers[h.name] = func(file string, options tags.Options) (template.HTML, error) {
    54  				if options == nil {
    55  					options = tags.Options{}
    56  				}
    57  				f, err := s.assetPath(file)
    58  				if err != nil {
    59  					return "", errors.WithStack(err)
    60  				}
    61  				return h.fn(f, options), nil
    62  			}
    63  		}(h)
    64  	}
    65  
    66  	return helpers
    67  }
    68  
    69  func jsTag(src string, options tags.Options) template.HTML {
    70  	if options["type"] == nil {
    71  		options["type"] = "text/javascript"
    72  	}
    73  
    74  	options["src"] = src
    75  	jsTag := tags.New("script", options)
    76  
    77  	return jsTag.HTML()
    78  }
    79  
    80  func cssTag(href string, options tags.Options) template.HTML {
    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  }
    94  
    95  func imgTag(src string, options tags.Options) template.HTML {
    96  	options["src"] = src
    97  	imgTag := tags.New("img", options)
    98  
    99  	return imgTag.HTML()
   100  }