Parsing templates using struct slice

I have a slice of struct, and I want to parse it using templates

type Data struct {
	ID   int
	Msg string
}

func main(){
	justin := Data{ID: 1, Msg: "Justin", }
	ruben := Data{ID: 2, Msg: "Ruben" }
	petyaT := Data{ ID: 1, Msg: "Petya Tereodor Pidgallo"}

	datas := []Data{justin, ruben, petyaT}

	tpl, err := template.New("msgs").Parse(`Hello range .datas {{.Msg}}`) 
	if err != nil {
		panic(err)
	}

	err = tpl.Execute(os.Stdout, datas)

	if err != nil {
		log.Fatalln(err)
	}
}

The result should simply be - Hello + all the names from the structs.
Not sure what im doing wrong
ps- I didn’t use parseGlob or parseFiles, because im trying to save the templates later in a database

The thing you pass to Execute() becomes . in the template, so you want

{{range .}}
    {{.Msg}}
{{end}}

(https://play.golang.org/p/Kn1YyQN_9cS)

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.