example_test.go 2.0 KB

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