How to generate HTML tables dynamically from data in Go?

To generate HTML tables dynamically from data in Go, you can follow these steps:

  1. Start by creating a struct to represent your data. This struct should contain the fields necessary for each table row. For example:
type Person struct { Name string Age int Email string }
  1. Load your data into a slice of this struct.
people := []Person{ {Name: "John Doe", Age: 30, Email: "[email protected]"}, {Name: "Jane Smith", Age: 25, Email: "[email protected]"}, // Add more data }
  1. Create a function to generate the HTML table. This function should take the data slice and return the generated HTML.
func generateTable(data []Person) string { header := "<tr><th>Name</th><th>Age</th><th>Email</th></tr>" rows := "" for _, person := range data { rows += "<tr><td>" + person.Name + "</td><td>" + strconv.Itoa(person.Age) + "</td><td>" + person.Email + "</td></tr>" } table := "<table>" + header + rows + "</table>" return table }
  1. Finally, call the generateTable function with your data slice to get the HTML table.
tableHTML := generateTable(people) fmt.Println(tableHTML)

This will output the dynamically generated HTML table based on your data. You can then use this HTML table however you need in your application.