example_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package fasttemplate
  2. import (
  3. "fmt"
  4. "io"
  5. "log"
  6. "net/url"
  7. )
  8. func ExampleTemplate() {
  9. template := "http://{{host}}/?foo={{bar}}{{bar}}&q={{query}}&baz={{baz}}"
  10. t, err := NewTemplate(template, "{{", "}}")
  11. if err != nil {
  12. log.Fatalf("unexpected error when parsing template: %s", err)
  13. }
  14. // Substitution map.
  15. // Since "baz" tag is missing in the map, it will be substituted
  16. // by an empty string.
  17. m := map[string]interface{}{
  18. "host": "google.com", // string - convenient
  19. "bar": []byte("foobar"), // byte slice - the fastest
  20. // TagFunc - flexible value. TagFunc is called only if the given
  21. // tag exists in the template.
  22. "query": TagFunc(func(w io.Writer, tag string) (int, error) {
  23. return w.Write([]byte(url.QueryEscape(tag + "=world")))
  24. }),
  25. }
  26. s := t.ExecuteString(m)
  27. fmt.Printf("%s", s)
  28. // Output:
  29. // http://google.com/?foo=foobarfoobar&q=query%3Dworld&baz=
  30. }
  31. func ExampleTagFunc() {
  32. template := "foo[baz]bar"
  33. t, err := NewTemplate(template, "[", "]")
  34. if err != nil {
  35. log.Fatalf("unexpected error when parsing template: %s", err)
  36. }
  37. bazSlice := [][]byte{[]byte("123"), []byte("456"), []byte("789")}
  38. m := map[string]interface{}{
  39. // Always wrap the function into TagFunc.
  40. //
  41. // "baz" tag function writes bazSlice contents into w.
  42. "baz": TagFunc(func(w io.Writer, tag string) (int, error) {
  43. var nn int
  44. for _, x := range bazSlice {
  45. n, err := w.Write(x)
  46. if err != nil {
  47. return nn, err
  48. }
  49. nn += n
  50. }
  51. return nn, nil
  52. }),
  53. }
  54. s := t.ExecuteString(m)
  55. fmt.Printf("%s", s)
  56. // Output:
  57. // foo123456789bar
  58. }
  59. func ExampleTemplate_ExecuteFuncString() {
  60. template := "Hello, [user]! You won [prize]!!! [foobar]"
  61. t, err := NewTemplate(template, "[", "]")
  62. if err != nil {
  63. log.Fatalf("unexpected error when parsing template: %s", err)
  64. }
  65. s := t.ExecuteFuncString(func(w io.Writer, tag string) (int, error) {
  66. switch tag {
  67. case "user":
  68. return w.Write([]byte("John"))
  69. case "prize":
  70. return w.Write([]byte("$100500"))
  71. default:
  72. return w.Write([]byte(fmt.Sprintf("[unknown tag %q]", tag)))
  73. }
  74. })
  75. fmt.Printf("%s", s)
  76. // Output:
  77. // Hello, John! You won $100500!!! [unknown tag "foobar"]
  78. }