在等待数据加载时,Golang显示静态HTML模板。

huangapple go评论95阅读模式
英文:

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模板的静态部分,然后在ShowWwResultShowHoursResult准备好后填充页面?

英文:

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.

huangapple
  • 本文由 发表于 2017年7月27日 07:06:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/45338830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定