关于golang tmplate怎么样传递值,以前的调查结果是只能用struct,但是最近开一个开源source,发现他竟然用的是map[string]interface{},百思不得其解,所以用一下代码进行验证。
PS,哎,golang的文档还是太弱了啊。
package main import ( "fmt" "html/template" "net/http" "os" ) type Person struct { Name string Age int Emails []string Company string Role string } const templ = ` name is {{.name}} Company is {{.resources.Company}} ` func Handler(w http.ResponseWriter,r *http.Request) { chxd := Person{Company: "Intel",Name: "chxd"}} t := template.New("Person template") t,err := t.Parse(templ) checkError(err) var tmp map[string]interface{} = map[string]interface{}{"name":"macs","resources":chxd} err = t.Execute(w,tmp) checkError(err) } func main() { http.HandleFunc("/",Handler) http.ListenAndServe(":8888",nil) } func checkError(err error) { if err != nil { fmt.Println("Fatal error ",err.Error()) os.Exit(1) } }原文链接:https://www.f2er.com/go/191304.html