Pass Multiple Values to Template

(Pete Tromblee) #1

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 {
	defer rows.Close()

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

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

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


(Norbert Melzer) #2

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

(Pete Tromblee) #3

Could you tell me what the struct would look like?

(Johan Dahl) #4

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

(Pete Tromblee) #5

Great. Thank you.