template.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. // Package fasttemplate implements simple and fast template library.
  2. //
  3. // Fasttemplate is faster than text/template, strings.Replace
  4. // and strings.Replacer.
  5. //
  6. // Fasttemplate ideally fits for fast and simple placeholders' substitutions.
  7. package fasttemplate
  8. import (
  9. "bytes"
  10. "fmt"
  11. "github.com/valyala/bytebufferpool"
  12. "io"
  13. )
  14. // ExecuteFunc calls f on each template tag (placeholder) occurrence.
  15. //
  16. // Returns the number of bytes written to w.
  17. //
  18. // This function is optimized for constantly changing templates.
  19. // Use Template.ExecuteFunc for frozen templates.
  20. func ExecuteFunc(template, startTag, endTag string, w io.Writer, f TagFunc) (int64, error) {
  21. s := unsafeString2Bytes(template)
  22. a := unsafeString2Bytes(startTag)
  23. b := unsafeString2Bytes(endTag)
  24. var nn int64
  25. var ni int
  26. var err error
  27. for {
  28. n := bytes.Index(s, a)
  29. if n < 0 {
  30. break
  31. }
  32. ni, err = w.Write(s[:n])
  33. nn += int64(ni)
  34. if err != nil {
  35. return nn, err
  36. }
  37. s = s[n+len(a):]
  38. n = bytes.Index(s, b)
  39. if n < 0 {
  40. // cannot find end tag - just write it to the output.
  41. ni, _ = w.Write(a)
  42. nn += int64(ni)
  43. break
  44. }
  45. ni, err = f(w, unsafeBytes2String(s[:n]))
  46. nn += int64(ni)
  47. s = s[n+len(b):]
  48. }
  49. ni, err = w.Write(s)
  50. nn += int64(ni)
  51. return nn, err
  52. }
  53. // Execute substitutes template tags (placeholders) with the corresponding
  54. // values from the map m and writes the result to the given writer w.
  55. //
  56. // Substitution map m may contain values with the following types:
  57. // * []byte - the fastest value type
  58. // * string - convenient value type
  59. // * TagFunc - flexible value type
  60. //
  61. // Returns the number of bytes written to w.
  62. //
  63. // This function is optimized for constantly changing templates.
  64. // Use Template.Execute for frozen templates.
  65. func Execute(template, startTag, endTag string, w io.Writer, m map[string]interface{}) (int64, error) {
  66. return ExecuteFunc(template, startTag, endTag, w, func(w io.Writer, tag string) (int, error) { return stdTagFunc(w, tag, m) })
  67. }
  68. // ExecuteFuncString calls f on each template tag (placeholder) occurrence
  69. // and substitutes it with the data written to TagFunc's w.
  70. //
  71. // Returns the resulting string.
  72. //
  73. // This function is optimized for constantly changing templates.
  74. // Use Template.ExecuteFuncString for frozen templates.
  75. func ExecuteFuncString(template, startTag, endTag string, f TagFunc) string {
  76. tagsCount := bytes.Count(unsafeString2Bytes(template), unsafeString2Bytes(startTag))
  77. if tagsCount == 0 {
  78. return template
  79. }
  80. bb := byteBufferPool.Get()
  81. if _, err := ExecuteFunc(template, startTag, endTag, bb, f); err != nil {
  82. panic(fmt.Sprintf("unexpected error: %s", err))
  83. }
  84. s := string(bb.B)
  85. bb.Reset()
  86. byteBufferPool.Put(bb)
  87. return s
  88. }
  89. var byteBufferPool bytebufferpool.Pool
  90. // ExecuteString substitutes template tags (placeholders) with the corresponding
  91. // values from the map m and returns the result.
  92. //
  93. // Substitution map m may contain values with the following types:
  94. // * []byte - the fastest value type
  95. // * string - convenient value type
  96. // * TagFunc - flexible value type
  97. //
  98. // This function is optimized for constantly changing templates.
  99. // Use Template.ExecuteString for frozen templates.
  100. func ExecuteString(template, startTag, endTag string, m map[string]interface{}) string {
  101. return ExecuteFuncString(template, startTag, endTag, func(w io.Writer, tag string) (int, error) { return stdTagFunc(w, tag, m) })
  102. }
  103. // Template implements simple template engine, which can be used for fast
  104. // tags' (aka placeholders) substitution.
  105. type Template struct {
  106. template string
  107. startTag string
  108. endTag string
  109. texts [][]byte
  110. tags []string
  111. byteBufferPool bytebufferpool.Pool
  112. }
  113. // New parses the given template using the given startTag and endTag
  114. // as tag start and tag end.
  115. //
  116. // The returned template can be executed by concurrently running goroutines
  117. // using Execute* methods.
  118. //
  119. // New panics if the given template cannot be parsed. Use NewTemplate instead
  120. // if template may contain errors.
  121. func New(template, startTag, endTag string) *Template {
  122. t, err := NewTemplate(template, startTag, endTag)
  123. if err != nil {
  124. panic(err)
  125. }
  126. return t
  127. }
  128. // NewTemplate parses the given template using the given startTag and endTag
  129. // as tag start and tag end.
  130. //
  131. // The returned template can be executed by concurrently running goroutines
  132. // using Execute* methods.
  133. func NewTemplate(template, startTag, endTag string) (*Template, error) {
  134. var t Template
  135. err := t.Reset(template, startTag, endTag)
  136. if err != nil {
  137. return nil, err
  138. }
  139. return &t, nil
  140. }
  141. // TagFunc can be used as a substitution value in the map passed to Execute*.
  142. // Execute* functions pass tag (placeholder) name in 'tag' argument.
  143. //
  144. // TagFunc must be safe to call from concurrently running goroutines.
  145. //
  146. // TagFunc must write contents to w and return the number of bytes written.
  147. type TagFunc func(w io.Writer, tag string) (int, error)
  148. // Reset resets the template t to new one defined by
  149. // template, startTag and endTag.
  150. //
  151. // Reset allows Template object re-use.
  152. //
  153. // Reset may be called only if no other goroutines call t methods at the moment.
  154. func (t *Template) Reset(template, startTag, endTag string) error {
  155. // Keep these vars in t, so GC won't collect them and won't break
  156. // vars derived via unsafe*
  157. t.template = template
  158. t.startTag = startTag
  159. t.endTag = endTag
  160. t.texts = t.texts[:0]
  161. t.tags = t.tags[:0]
  162. if len(startTag) == 0 {
  163. panic("startTag cannot be empty")
  164. }
  165. if len(endTag) == 0 {
  166. panic("endTag cannot be empty")
  167. }
  168. s := unsafeString2Bytes(template)
  169. a := unsafeString2Bytes(startTag)
  170. b := unsafeString2Bytes(endTag)
  171. tagsCount := bytes.Count(s, a)
  172. if tagsCount == 0 {
  173. return nil
  174. }
  175. if tagsCount+1 > cap(t.texts) {
  176. t.texts = make([][]byte, 0, tagsCount+1)
  177. }
  178. if tagsCount > cap(t.tags) {
  179. t.tags = make([]string, 0, tagsCount)
  180. }
  181. for {
  182. n := bytes.Index(s, a)
  183. if n < 0 {
  184. t.texts = append(t.texts, s)
  185. break
  186. }
  187. t.texts = append(t.texts, s[:n])
  188. s = s[n+len(a):]
  189. n = bytes.Index(s, b)
  190. if n < 0 {
  191. return fmt.Errorf("Cannot find end tag=%q in the template=%q starting from %q", endTag, template, s)
  192. }
  193. t.tags = append(t.tags, unsafeBytes2String(s[:n]))
  194. s = s[n+len(b):]
  195. }
  196. return nil
  197. }
  198. // ExecuteFunc calls f on each template tag (placeholder) occurrence.
  199. //
  200. // Returns the number of bytes written to w.
  201. //
  202. // This function is optimized for frozen templates.
  203. // Use ExecuteFunc for constantly changing templates.
  204. func (t *Template) ExecuteFunc(w io.Writer, f TagFunc) (int64, error) {
  205. var nn int64
  206. n := len(t.texts) - 1
  207. if n == -1 {
  208. ni, err := w.Write(unsafeString2Bytes(t.template))
  209. return int64(ni), err
  210. }
  211. for i := 0; i < n; i++ {
  212. ni, err := w.Write(t.texts[i])
  213. nn += int64(ni)
  214. if err != nil {
  215. return nn, err
  216. }
  217. ni, err = f(w, t.tags[i])
  218. nn += int64(ni)
  219. if err != nil {
  220. return nn, err
  221. }
  222. }
  223. ni, err := w.Write(t.texts[n])
  224. nn += int64(ni)
  225. return nn, err
  226. }
  227. // Execute substitutes template tags (placeholders) with the corresponding
  228. // values from the map m and writes the result to the given writer w.
  229. //
  230. // Substitution map m may contain values with the following types:
  231. // * []byte - the fastest value type
  232. // * string - convenient value type
  233. // * TagFunc - flexible value type
  234. //
  235. // Returns the number of bytes written to w.
  236. func (t *Template) Execute(w io.Writer, m map[string]interface{}) (int64, error) {
  237. return t.ExecuteFunc(w, func(w io.Writer, tag string) (int, error) { return stdTagFunc(w, tag, m) })
  238. }
  239. // ExecuteFuncString calls f on each template tag (placeholder) occurrence
  240. // and substitutes it with the data written to TagFunc's w.
  241. //
  242. // Returns the resulting string.
  243. //
  244. // This function is optimized for frozen templates.
  245. // Use ExecuteFuncString for constantly changing templates.
  246. func (t *Template) ExecuteFuncString(f TagFunc) string {
  247. bb := t.byteBufferPool.Get()
  248. if _, err := t.ExecuteFunc(bb, f); err != nil {
  249. panic(fmt.Sprintf("unexpected error: %s", err))
  250. }
  251. s := string(bb.Bytes())
  252. bb.Reset()
  253. t.byteBufferPool.Put(bb)
  254. return s
  255. }
  256. // ExecuteString substitutes template tags (placeholders) with the corresponding
  257. // values from the map m and returns the result.
  258. //
  259. // Substitution map m may contain values with the following types:
  260. // * []byte - the fastest value type
  261. // * string - convenient value type
  262. // * TagFunc - flexible value type
  263. //
  264. // This function is optimized for frozen templates.
  265. // Use ExecuteString for constantly changing templates.
  266. func (t *Template) ExecuteString(m map[string]interface{}) string {
  267. return t.ExecuteFuncString(func(w io.Writer, tag string) (int, error) { return stdTagFunc(w, tag, m) })
  268. }
  269. func stdTagFunc(w io.Writer, tag string, m map[string]interface{}) (int, error) {
  270. v := m[tag]
  271. if v == nil {
  272. return 0, nil
  273. }
  274. switch value := v.(type) {
  275. case []byte:
  276. return w.Write(value)
  277. case string:
  278. return w.Write([]byte(value))
  279. case TagFunc:
  280. return value(w, tag)
  281. default:
  282. panic(fmt.Sprintf("tag=%q contains unexpected value type=%#v. Expected []byte, string or TagFunc", tag, v))
  283. }
  284. }