go template example
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.1 KiB

5 years ago
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "strings"
  6. "text/template"
  7. )
  8. type Person struct {
  9. Name string
  10. Age int
  11. }
  12. func main() {
  13. var err error
  14. funcMap := template.FuncMap{
  15. "title": strings.Title,
  16. }
  17. base, err := Asset("templates/base.txt")
  18. if err != nil {
  19. panic(err)
  20. }
  21. tmpl, err := template.New("base").Funcs(funcMap).Parse(string(base))
  22. templates := make(map[string]*template.Template)
  23. templateFiles := []struct {
  24. name string
  25. path string
  26. }{
  27. {"body", "templates/body.txt"},
  28. {"detail", "templates/detail.txt"},
  29. {"pic", "templates/pic.txt"},
  30. }
  31. for _, tf := range templateFiles {
  32. a, err := Asset(tf.path)
  33. if err != nil {
  34. panic(err)
  35. }
  36. t, err := tmpl.Clone()
  37. if err != nil {
  38. panic(err)
  39. }
  40. t, err = t.Parse(string(a))
  41. templates[tf.name] = t
  42. }
  43. person := Person{"bilbo", 111}
  44. for _, name := range []string{"body", "detail", "pic"} {
  45. fmt.Println("--------------------------------------")
  46. err = templates[name].Execute(os.Stdout, person)
  47. if err != nil {
  48. panic(err)
  49. }
  50. }
  51. fmt.Println("--------------------------------------")
  52. }