text-template

Complete the code in line A, to generate content with text template for at most 3 tiers. The expected output is as follows:A B C D

  1. package main
  2. import (
  3. "log"
  4. "os"
  5. "text/template"
  6. )
  7. func main() {
  8. const tpl = `
  9. ` // A
  10. type Tree struct {
  11. Name string
  12. Children []Tree
  13. }
  14. root := Tree{
  15. "A", []Tree{
  16. Tree{"B", []Tree{
  17. Tree{"C", []Tree{}},
  18. }},
  19. Tree{"D", []Tree{}},
  20. },
  21. }
  22. t := template.Must(template.New("tree").Parse(tpl))
  23. err := t.Execute(os.Stdout, root)
  24. if err != nil {
  25. log.Fatalf("executing template:", err)
  26. }
  27. }

Answer

  1. package main
  2. import (
  3. "log"
  4. "os"
  5. "text/template"
  6. )
  7. func main() {
  8. const tpl = `{{.Name}}{{range $child := .Children}}
  9. {{$child.Name}}{{range $grandchild := $child.Children}}
  10. {{$grandchild.Name}}{{end}}{{end}}
  11. ` // A
  12. type Tree struct {
  13. Name string
  14. Children []Tree
  15. }
  16. root := Tree{
  17. "A", []Tree{
  18. Tree{"B", []Tree{
  19. Tree{"C", []Tree{}},
  20. }},
  21. Tree{"D", []Tree{}},
  22. },
  23. }
  24. t := template.Must(template.New("tree").Parse(tpl))
  25. err := t.Execute(os.Stdout, root)
  26. if err != nil {
  27. log.Fatalf("executing template:", err)
  28. }
  29. }