templates.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package templates
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "strings"
  6. "text/template"
  7. )
  8. // basicFunctions are the set of initial
  9. // functions provided to every template.
  10. var basicFunctions = template.FuncMap{
  11. "json": func(v interface{}) string {
  12. buf := &bytes.Buffer{}
  13. enc := json.NewEncoder(buf)
  14. enc.SetEscapeHTML(false)
  15. enc.Encode(v)
  16. // Remove the trailing new line added by the encoder
  17. return strings.TrimSpace(buf.String())
  18. },
  19. "split": strings.Split,
  20. "join": strings.Join,
  21. "title": strings.Title,
  22. "lower": strings.ToLower,
  23. "upper": strings.ToUpper,
  24. "pad": padWithSpace,
  25. "truncate": truncateWithLength,
  26. }
  27. // HeaderFunctions are used to created headers of a table.
  28. // This is a replacement of basicFunctions for header generation
  29. // because we want the header to remain intact.
  30. // Some functions like `split` are irrevelant so not added.
  31. var HeaderFunctions = template.FuncMap{
  32. "json": func(v string) string {
  33. return v
  34. },
  35. "title": func(v string) string {
  36. return v
  37. },
  38. "lower": func(v string) string {
  39. return v
  40. },
  41. "upper": func(v string) string {
  42. return v
  43. },
  44. "truncate": func(v string, l int) string {
  45. return v
  46. },
  47. }
  48. // Parse creates a new anonymous template with the basic functions
  49. // and parses the given format.
  50. func Parse(format string) (*template.Template, error) {
  51. return NewParse("", format)
  52. }
  53. // NewParse creates a new tagged template with the basic functions
  54. // and parses the given format.
  55. func NewParse(tag, format string) (*template.Template, error) {
  56. return template.New(tag).Funcs(basicFunctions).Parse(format)
  57. }
  58. // padWithSpace adds whitespace to the input if the input is non-empty
  59. func padWithSpace(source string, prefix, suffix int) string {
  60. if source == "" {
  61. return source
  62. }
  63. return strings.Repeat(" ", prefix) + source + strings.Repeat(" ", suffix)
  64. }
  65. // truncateWithLength truncates the source string up to the length provided by the input
  66. func truncateWithLength(source string, length int) string {
  67. if len(source) < length {
  68. return source
  69. }
  70. return source[:length]
  71. }