Populate HTML table using slices for the rows?

I’d like to be able to populate a table using slices to hold the data for the rows in the table.

I made a server to practice this so here’s my handler and generateTable() function.

func handler(w http.ResponseWriter, r *http.Request) {
	t, err := template.ParseFiles("tableTemplate.html")
	t.Execute(w, row)

func generateTable() {
	row := new(Row)
	rows := []*Row{}

	row.thailandTime = "10:01"
	row.englandTime = "10:02"
	row.x = 2
	row.y = 3
	row.valid = true

	rows = append(rows, row)

I have a separate HTML file which i’d like to just have to type in loop and then it will loop through the slice and populate the table.

I’m fairly new to this so any help/advice will be much appreciated.

Check out this working example:

package main

import (

func main() {
	http.HandleFunc("/", handler)
	log.Fatal(http.ListenAndServe(":8080", nil))

func handler(w http.ResponseWriter, r *http.Request) {
	rows := []Row{
		{ThailandTime: "10:01", EnglandTime: "10:02", X: 2, Y: 3, Valid: true},
		{ThailandTime: "11:01", EnglandTime: "11:02", X: 3, Y: 4, Valid: false},
	if err := index.Execute(w, rows); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)

type Row struct {
	ThailandTime string
	EnglandTime  string
	X            int
	Y            int
	Valid        bool

// Replace with:
// var templates = template.Must(template.ParseFiles("tableTemplate.html"))
var index = template.Must(template.New("index").Parse(indexTmpl))

const indexTmpl = `<!DOCTYPE html>
		<meta charset="UTF-8">
		<title>My page</title>
		{{range .}}

I recommend reading Writing Web Applications.


Perfect! Just what i was looking for, thanks for your efforts!

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