英文:
Golang display static HTML template while waiting for data to load
问题
我有一个设置好的路由,用于响应动态的HTML模板。
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)
}
我的问题是,获取数据需要很长时间,页面在等待数据返回后才会渲染HTML。
在等待GetWw()
和GetHours()
完成的同时,我该如何返回任何东西?是否有办法显示HTML模板的静态部分,然后在ShowWwResult
和ShowHoursResult
准备好后填充页面?
英文:
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?
答案1
得分: 2
不,最好的方法是先提供模板,然后使用ajax调用到一个返回所需数据的json的端点来填充它。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论