github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/06_xmljson/template/func/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"html/template"
     6  	"os"
     7  	"strings"
     8  )
     9  
    10  type Friend struct {
    11  	Fname string
    12  }
    13  type Person struct {
    14  	UserName string
    15  	Emails   []string
    16  	Friends  []*Friend
    17  }
    18  
    19  func EmailDealWith(args ...interface{}) string {
    20  	ok := false
    21  	var s string
    22  	if len(args) == 1 {
    23  		s, ok = args[0].(string)
    24  	}
    25  	if !ok {
    26  		s = fmt.Sprint(args...)
    27  	}
    28  	// find the @ symbol
    29  	substrs := strings.Split(s, "@")
    30  	if len(substrs) != 2 {
    31  		return s
    32  	}
    33  	// replace the @ by " at "
    34  	return (substrs[0] + " at " + substrs[1])
    35  }
    36  
    37  func main() {
    38  	f1 := Friend{Fname: "minux.ma"}
    39  	f2 := Friend{Fname: "xushiwei"}
    40  	t := template.New("fieldname example")
    41  
    42  	t = t.Funcs(template.FuncMap{"emailDeal": EmailDealWith})
    43  	t = template.Must(t.Parse(`hello {{.UserName}}!
    44          {{range .Emails}}
    45          an emails {{.|emailDeal}}
    46          {{end}}
    47          {{with .Friends}}
    48          {{range .}}
    49          my friend name is {{.Fname}}
    50          {{end}}
    51          {{end}}
    52          `))
    53  	p := Person{UserName: "hanru",
    54  		Emails:  []string{"hanru@beego.me", "hanru723@gmail.com"},
    55  		Friends: []*Friend{&f1, &f2}}
    56  	t.Execute(os.Stdout, p)
    57  }