Populate HTML dropdown using values from a string map?

I’m fairly new to Go, I made a local server with a dropdown and so I’d like to get the values from the stringmap I’ve made in my .go file, rather than have them hardcoded into my html file.

Here’s my code in my server.go file:

func handler(w http.ResponseWriter, r *http.Request) {

	t, err := template.ParseFiles("edit.html")
	if err != nil {
		log.Fatalln(err)
	}

	err = t.Execute(w, nil)
	if err != nil {
		log.Fatalln(err)
	}
}

func main() {
	colours := map[string]string{
		"1": "blue",
		"2": "red",
		"3": "yellow",
	}
	for k, v := range colors{
		//append to dropdown
	}

	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)
}

And here’s my code in my edit.html file:

<select>
  <option value=""></option>
  <option value=""></option>
  <option value=""></option>
  <option value=""></option>
</select>

What’s the best way to go about this? Thanks.

Your second argument to Execute() should be the data you wish to iterate over; it’s also called a context. Then your template (the .html file) will iterate that data using {{range}} - see text/template for details (although you’ll probably want html/template in reality).

2 Likes

I hope this will help you: http://beego.me/

Also, don’t forget that a map returns a random order, which may not matter if your web control ultimately sorts the array.

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