Pass Multiple Values to Template

I’m new to Go and working on a sample web app to get familiar with the language. I need to pass multiple values to a template. Below is code that works great and I display the label data in a template. I currently pass “labels” to the template but I also need to pass a cookie value. Thanks

func createLabels(w http.ResponseWriter, req *http.Request) {

	rows, err := db.Query("SELECT * FROM labelTypes")

	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	labels := make([]*Label, 0)
	for rows.Next() {
		lb := new(Label)
		err := rows.Scan(&lb.Id, &lb.Name)
		if err != nil {
			log.Fatal(err)
		}
		labels = append(labels, lb)
	}

	if err = rows.Err(); err != nil {
		log.Fatal(err)
	}


	tpl.ExecuteTemplate(w, "labels.html", labels)

}

Use a struct which you populate with the data in the fields.

Could you tell me what the struct would look like?

Use an anonymous struct. You declare it and populate it just once. Remember all fields in the struct must be Uppercase so they are exported and visible inside the template.

data := struct {
		Labels []Label
		Cookie http.Cookie
	}{
		Labels: labels,
		Cookie: c,
	}

and then pass data to ExecuteTemplate. In the template can you access cookie with .Cookie and labels with .Labels

2 Likes

Great. Thank you.

1 Like