How to incrementally write html template in go

WBOY
Release: 2024-02-06 09:50:08
forward
679 people have browsed it

How to incrementally write html template in go

Question content

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)
    }
}
Copy after login


Correct answer


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)
Copy after login

}

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!