/lang/template.go

https://github.com/grailbio/reflow · Go · 58 lines · 44 code · 6 blank · 8 comment · 6 complexity · b754a208a9a7c5df8c802b896a21c1ea MD5 · raw file

  1. // Copyright 2017 GRAIL, Inc. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package lang
  5. import (
  6. "errors"
  7. "strings"
  8. )
  9. var errInvalidTemplate = errors.New("invalid template")
  10. // template implements a templating language: it parses identifiers
  11. // enclosed by '{{' and '}}'; these identifiers are placed (in order)
  12. // in Idents.
  13. type template struct {
  14. Idents []string
  15. Fragments []string
  16. }
  17. // newTemplate creates a new template from string s,
  18. // returning errInvalidTemplate on error.
  19. func newTemplate(s string) (*template, error) {
  20. s = strings.Replace(s, "%", "%%", -1)
  21. t := &template{}
  22. for {
  23. beg := strings.Index(s, `{{`)
  24. if beg < 0 {
  25. break
  26. }
  27. t.Fragments = append(t.Fragments, s[:beg])
  28. if len(s) < 4 {
  29. return nil, errInvalidTemplate
  30. }
  31. s = s[beg+2:]
  32. end := strings.Index(s, `}}`)
  33. if end < 0 {
  34. return nil, errInvalidTemplate
  35. }
  36. t.Idents = append(t.Idents, s[:end])
  37. s = s[end+2:]
  38. }
  39. t.Fragments = append(t.Fragments, s)
  40. return t, nil
  41. }
  42. func (t *template) Format(args ...string) string {
  43. s := ""
  44. for i := range t.Fragments {
  45. s += t.Fragments[i]
  46. if i >= len(t.Idents) {
  47. continue
  48. }
  49. s += args[i]
  50. }
  51. return s
  52. }