To generate HTML tables dynamically from data in Go, you can follow these steps:
type Person struct {
Name string
Age int
Email string
}
people := []Person{
{Name: "John Doe", Age: 30, Email: "[email protected]"},
{Name: "Jane Smith", Age: 25, Email: "[email protected]"},
// Add more data
}
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
}
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.