template.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package core
  2. import (
  3. "bytes"
  4. "text/template"
  5. "github.com/mgutz/ansi"
  6. )
  7. var DisableColor = false
  8. var (
  9. HelpInputRune = '?'
  10. ErrorIcon = "✘"
  11. HelpIcon = "ⓘ"
  12. QuestionIcon = "?"
  13. MarkedOptionIcon = "◉"
  14. UnmarkedOptionIcon = "◯"
  15. SelectFocusIcon = "❯"
  16. )
  17. var TemplateFuncs = map[string]interface{}{
  18. // Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format
  19. "color": func(color string) string {
  20. if DisableColor {
  21. return ""
  22. }
  23. return ansi.ColorCode(color)
  24. },
  25. "HelpInputRune": func() string {
  26. return string(HelpInputRune)
  27. },
  28. "ErrorIcon": func() string {
  29. return ErrorIcon
  30. },
  31. "HelpIcon": func() string {
  32. return HelpIcon
  33. },
  34. "QuestionIcon": func() string {
  35. return QuestionIcon
  36. },
  37. "MarkedOptionIcon": func() string {
  38. return MarkedOptionIcon
  39. },
  40. "UnmarkedOptionIcon": func() string {
  41. return UnmarkedOptionIcon
  42. },
  43. "SelectFocusIcon": func() string {
  44. return SelectFocusIcon
  45. },
  46. }
  47. var memoizedGetTemplate = map[string]*template.Template{}
  48. func getTemplate(tmpl string) (*template.Template, error) {
  49. if t, ok := memoizedGetTemplate[tmpl]; ok {
  50. return t, nil
  51. }
  52. t, err := template.New("prompt").Funcs(TemplateFuncs).Parse(tmpl)
  53. if err != nil {
  54. return nil, err
  55. }
  56. memoizedGetTemplate[tmpl] = t
  57. return t, nil
  58. }
  59. func RunTemplate(tmpl string, data interface{}) (string, error) {
  60. t, err := getTemplate(tmpl)
  61. if err != nil {
  62. return "", err
  63. }
  64. buf := bytes.NewBufferString("")
  65. err = t.Execute(buf, data)
  66. if err != nil {
  67. return "", err
  68. }
  69. return buf.String(), err
  70. }