Evan Hessler
Evan Hessler

Reputation: 337

Golang display static HTML template while waiting for data to load

I have a route set up which responds with a dynamic HTML template.

package main

import (
    "net/http"
    "html/template"
)

func index(w http.ResponseWriter, r *http.Request) {
    showWwResult, _ := GetWw()
    showHoursResult, _ := GetHours()

    type Data struct {
        ShowWwResult   []IssueResult
        ShowHoursResult Page
    }

    data := Data{showWwResult, showHoursResult}

    var templates = template.Must(template.ParseFiles("templates/index.html", "templates/ww.html", "templates/hours.html"))
    templates.ExecuteTemplate(w, "indexPage", data)
}

My problem is, it takes a very long time to gather the data and the page waits for this to return before rendering the HTML.

How can I get it to return something, anything, while I wait for GetWw() and GetHours() to finish? Is there any way to display the static part of my HTML template and then populate the page with ShowWwResult and ShowHoursResult when they're ready?

Upvotes: 0

Views: 888

Answers (1)

OneOfOne
OneOfOne

Reputation: 99224

No, the best way is to serve the template then populate it using ajax calls to an endpoint that returns json with the data you want to use.

Upvotes: 2

Related Questions