templates.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package templates
  2. import (
  3. "encoding/json"
  4. "strings"
  5. "text/template"
  6. )
  7. // basicFunctions are the set of initial
  8. // functions provided to every template.
  9. var basicFunctions = template.FuncMap{
  10. "json": func(v interface{}) string {
  11. a, _ := json.Marshal(v)
  12. return string(a)
  13. },
  14. "split": strings.Split,
  15. "join": strings.Join,
  16. "title": strings.Title,
  17. "lower": strings.ToLower,
  18. "upper": strings.ToUpper,
  19. "pad": padWithSpace,
  20. }
  21. // Parse creates a new annonymous template with the basic functions
  22. // and parses the given format.
  23. func Parse(format string) (*template.Template, error) {
  24. return NewParse("", format)
  25. }
  26. // NewParse creates a new tagged template with the basic functions
  27. // and parses the given format.
  28. func NewParse(tag, format string) (*template.Template, error) {
  29. return template.New(tag).Funcs(basicFunctions).Parse(format)
  30. }
  31. // padWithSpace adds whitespace to the input if the input is non-empty
  32. func padWithSpace(source string, prefix, suffix int) string {
  33. if source == "" {
  34. return source
  35. }
  36. return strings.Repeat(" ", prefix) + source + strings.Repeat(" ", suffix)
  37. }