example_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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) (int, error) {
  23. return w.Write([]byte(url.QueryEscape("hello=world")))
  24. }),
  25. }
  26. s := t.ExecuteString(m)
  27. fmt.Printf("%s", s)
  28. // Output:
  29. // http://google.com/?foo=foobarfoobar&q=hello%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) (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. }