templates.go 830 B

123456789101112131415161718192021222324252627282930313233
  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. }
  20. // Parse creates a new annonymous template with the basic functions
  21. // and parses the given format.
  22. func Parse(format string) (*template.Template, error) {
  23. return NewParse("", format)
  24. }
  25. // NewParse creates a new tagged template with the basic functions
  26. // and parses the given format.
  27. func NewParse(tag, format string) (*template.Template, error) {
  28. return template.New(tag).Funcs(basicFunctions).Parse(format)
  29. }