To create HTML tables with sorting and filtering functionality in Go, you can use the following steps:
{{define "table"}}
<table>
<thead>
<tr>
<th><a href="?sort=id">ID</a></th>
<th><a href="?sort=name">Name</a></th>
<th><a href="?sort=age">Age</a></th>
</tr>
</thead>
<tbody>
{{range .}}
<tr>
<td>{{.ID}}</td>
<td>{{.Name}}</td>
<td>{{.Age}}</td>
</tr>
{{end}}
</tbody>
</table>
{{end}}
type User struct {
ID int
Name string
Age int
}
net/http
package:func tableHandler(w http.ResponseWriter, r *http.Request) {
// Retrieve the data and store it in a slice of User structs
data := []User{
{ID: 1, Name: "John Doe", Age: 30},
{ID: 2, Name: "Jane Smith", Age: 25},
// ...
}
// Apply sorting based on the "sort" query parameter
sortBy := r.URL.Query().Get("sort")
switch sortBy {
case "id":
sort.Slice(data, func(i, j int) bool { return data[i].ID < data[j].ID })
case "name":
sort.Slice(data, func(i, j int) bool { return data[i].Name < data[j].Name })
case "age":
sort.Slice(data, func(i, j int) bool { return data[i].Age < data[j].Age })
}
// Render the HTML template
t := template.Must(template.New("table").ParseFiles("table.html"))
t.ExecuteTemplate(w, "table", data)
}
tableHandler
function as an HTTP handler for the desired URL path. For example, using the http.HandleFunc
function:func main() {
http.HandleFunc("/table", tableHandler)
http.ListenAndServe(":8080", nil)
}
Create a CSS file to style the table as desired. This step is optional but can greatly enhance the appearance of the table.
Create an HTML file (e.g., table.html
) that includes a link to the CSS file and invokes the template defined in step 1. For example:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
{{template "table" .}}
</body>
</html>
With these steps, accessing the /table
URL will display an HTML table with sorting and filtering functionality in Go, based on the data provided in the tableHandler
function. The table headers will have links that allow sorting by the corresponding column when clicked.