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) {
	generateTable()
	t, err := template.ParseFiles("tableTemplate.html")
	checkErr(err)
	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 (
	"html/template"
	"log"
	"net/http"
)

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>
<html>
	<head>
		<meta charset="UTF-8">
		<title>My page</title>
	</head>
	<body>
		<table>
			<tr>
				<th>ThailandTime</th>
				<th>EnglandTime</th>
				<th>X</th>
				<th>Y</th>
				<th>Valid</th>
			</tr>
		{{range .}}
			<tr>
				<td>{{.ThailandTime}}</td>
				<td>{{.EnglandTime}}</td>
				<td>{{.X}}</td>
				<td>{{.Y}}</td>
				<td>{{.Valid}}</td>
			</tr>
		{{end}}
		</table>
	</body>
</html>
`

I recommend reading Writing Web Applications.

2 Likes

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.