Golang如何模板化嵌套结构?

我正在尝试将 JSON 响应模板化到前端,我当前的结构是这样的:


    type Response struct {

    WhoisRecord struct {

        CreatedDate time.Time `json:"createdDate"`

        UpdatedDate time.Time `json:"updatedDate"`

        ExpiresDate time.Time `json:"expiresDate"`

        Registrant  struct {

            Name         string `json:"name"`

            Organization string `json:"organization"`

            Street1      string `json:"street1"`

            City         string `json:"city"`

            State        string `json:"state"`

            Country      string `json:"country"`

            CountryCode  string `json:"countryCode"`

            Email        string `json:"email"`

            Telephone    string `json:"telephone"`

            Fax          string `json:"fax"`

        } `json:"registrant"`

        AdministrativeContact struct {

            Name         string `json:"name"`

            Organization string `json:"organization"`

            Street1      string `json:"street1"`

            City         string `json:"city"`

            State        string `json:"state"`

            Country      string `json:"country"`

            CountryCode  string `json:"countryCode"`

            Email        string `json:"email"`

            Telephone    string `json:"telephone"`

            Fax          string `json:"fax"`

        } `json:"administrativeContact"`

        TechnicalContact struct {

            Name         string `json:"name"`

            Organization string `json:"organization"`

            Street1      string `json:"street1"`

            City         string `json:"city"`

            State        string `json:"state"`

}

然后我解组这个 json 响应,并将它传递到前端(我正在使用 GIN)


(响应被重新声明为res)


c.HTML(200,"homework.html", gin.H{

        "whois":    res,

    })

但这是我遇到问题的地方,代码可以工作,但我不确定如何模板化它,因为它是嵌套的。


例如,我想在单独的表格中显示注册人、管理人员和技术联系人的详细信息(返回的所有字段)。以及显示创建、更新和过期的日期。然后通过显示注册商、ips 和名称服务器(在本例中为 下的hostnames字段NameServers)来完成


但是这些都不起作用(我如何在一个字段中显示注册人姓名,然后在另一个字段中显示技术名称?我显然把模板搞砸了,我对它的理解有点歪曲)。我已经阅读了我所能阅读的所有内容,我试图划分结构并作为单独的结构,等等。没有任何工作。有人可以指出我正确的方向并举例吗?


谢谢!


梦里花落0921
浏览 183回答 1
1回答

海绵宝宝撒

模板字段相对于当前上下文 {{.}} 进行评估。以下使用包含“whois”作为键和res值的映射来评估模板:in.H{ "whois": res})的值{{.whois}}是您的结构,您可以从那里访问结构字段。所以你可以这样做:{{.whois.Registrant.Name}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go