I am building a web-based data browser called mavgo flight. I want large tables in sqlite to print continuously instead of the default behavior of only printing when all data is available. I tried running the template per row of data but failed.
func renderHTMLTable(w http.ResponseWriter, result *sqlx.Rows) { cols, err := result.Columns() if err != nil { log.Println(err, "renderHTMLTable") return } tmpl, err := template.ParseFiles("./templates/2d.html") if err != nil { log.Println("template failed", err) return } data := HTMLTable{} data.Cols = cols for result.Next() { cols, err := result.SliceScan() if err != nil { log.Println(w, err) break } s := make([]string, len(cols)) for i, v := range cols { s[i] = fmt.Sprint(v) } tmpl.Execute(w, s) } }
I gave up on being clever and did exactly what cerise suggested Function for incrementally writing rows:
func renderHTMLTable(w http.ResponseWriter, result *sqlx.Rows) { cols, err := result.Columns() if err != nil { log.Println(err, "renderHTMLTable") return } head, err := template.ParseFiles("./templates/head.html") if err != nil { log.Println("template failed", err) return } row, err := template.ParseFiles("./templates/row.html") if err != nil { log.Println("template failed", err) return } foot := ` </tbody> </table> </div> </body> </html>` head.Execute(w, cols) s := make([]string, len(cols)) for result.Next() { values, err := result.SliceScan() if err != nil { log.Println(w, err) break } for i, v := range values { s[i] = fmt.Sprint(v) } row.Execute(w, s) } fmt.Fprint(w, foot)
}
The above is the detailed content of How to incrementally write html template in go. For more information, please follow other related articles on the PHP Chinese website!