github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/03_form/template_demo_01.go (about)

     1  package main
     2  
     3  import (
     4  	"os"
     5  	"text/template"
     6  )
     7  
     8  type Friend struct {
     9  	Fname string
    10  }
    11  type Person struct {
    12  	UserName string
    13  	Emails   []string
    14  	Friends  []*Friend
    15  }
    16  
    17  func main() {
    18  	t := template.New("test")
    19  	t = template.Must(t.Parse(`
    20  	hello {{.UserName}}!
    21  	{{ range .Emails }}
    22  	an email {{ . }}
    23  	{{- end }}
    24  	{{ with .Friends }}
    25  	{{- range . }}
    26  	my friend name is {{.Fname}}
    27  	{{- end }}
    28  	{{ end }}
    29  `))
    30  	/*
    31  		{{- xxxx}} 去空白
    32  	*/
    33  
    34  	f1 := Friend{Fname: "xiaofang"}
    35  	f2 := Friend{Fname: "wugui"}
    36  	p := Person{UserName: "longshuai",
    37  		Emails:  []string{"a1@qq.com", "a2@gmail.com"},
    38  		Friends: []*Friend{&f1, &f2},
    39  	}
    40  	t.Execute(os.Stdout, p)
    41  }