templateに渡すdataの構造化【Go】
goファイルからtemplateへ渡すdataを、structを使って構造化します。
main.goです。
NPBの中にLeagueのポインタ型が2つ、Leagueの中にTeamのポインタ型のスライスがあります。
var tpl *template.Template type Team struct { Name string Est int } type League struct { Name string Teams []*Team } type NPB struct { Pacific, Central *League } func init() { tpl = template.Must(template.ParseFiles("tpl.gohtml")) } func main() { nf, err := os.Create("index.html") if err != nil { log.Fatal(err) } npb := &NPB{ Pacific: &League{ Name: "Pacific League", Teams: []*Team{ &Team{Name: "Lions", Est: 1950}, &Team{Name: "Hawks", Est: 1938}, &Team{Name: "Fighters", Est: 1946}, &Team{Name: "Buffaloes", Est: 1936}, &Team{Name: "Marines", Est: 1950}, &Team{Name: "Eagles", Est: 2005}, }, }, Central: &League{ Name: "Central League", Teams: []*Team{ &Team{Name: "Carp", Est: 1950}, &Team{Name: "Swallows", Est: 1950}, &Team{Name: "Giants", Est: 1934}, &Team{Name: "BayStars", Est: 1950}, &Team{Name: "Dragons", Est: 1936}, &Team{Name: "Tigers", Est: 1935}, }, }, } err = tpl.ExecuteTemplate(nf, "tpl.gohtml", npb) if err != nil { log.Fatalln(err) } }
続いてtpl.gohtmlです。
チェーンのように繋げることで、ネストされた構造体から取り出すことができます。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello World!</title> </head> <body> {{.Pacific.Name}}: {{range .Pacific.Teams}} // Teamsのスライス分だけループ処理 <li>{{.Name}}, {{.Est}}</li> // TeamのNameとEstを出力 {{end}} {{.Central.Name}}: {{range .Central.Teams}}} // Teamsのスライス分だけループ処理 <li>{{.Name}}, {{.Est}}</li> // TeamのNameとEstを出力 {{end}} </body> </html>
index.htmlは次のようになります。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello World!</title> </head> <body> Pacific League: <li>Lions, 1950</li> <li>Hawks, 1938</li> <li>Fighters, 1946</li> <li>Buffaloes, 1936</li> <li>Marines, 1950</li> <li>Eagles, 2005</li> Central League: <li>Carp, 1950</li> <li>Swallows, 1950</li> <li>Giants, 1934</li> <li>BayStars, 1950</li> <li>Dragons, 1936</li> <li>Tigers, 1935</li> </body> </html>
※空行を削除しています。