我正在尝试将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"`
Country string `json:"country"`
CountryCode string `json:"countryCode"`
Email string `json:"email"`
Telephone string `json:"telephone"`
Fax string `json:"fax"`
} `json:"technicalContact"`
DomainName string `json:"domainName"`
NameServers struct {
HostNames []string `json:"hostNames"`
} `json:"nameServers"`
RegistrarName string `json:"registrarName"`
Ips []string `json:"ips"`
} `json:"WhoisRecord"`
}
然后我解组该json响应,并将其传递到前端(我正在使用GIN)
(响应重新声明为 res )
c.HTML(200,"homework.html", gin.H{
"whois": res,
})
但这是我遇到问题的地方,代码可以工作,但是由于它是嵌套的,所以我不确定如何对其进行模板化。
例如,我想在单独的表格中显示“注册人”,“管理人员”和“技术联系方式”(返回的所有字段)。以及显示创建,更新和过期的日期。然后通过显示The registrar,ips和nameservers(在本例中为hostnames
下的NameServers
字段)来完成
我该如何在homework.html文件中提供此服务?我已经尝试了一切。通常我只会做类似的事情:
要显示IP:
{{ range .Ips }}
<div>
<p>IP</p>
<h6>{{ . }}</h6>
</div>
{{end}}
显示寄存器数据:
<div>
<p>Name</p>
<h6>{{ .Name }}</h6>
<p>Email</p>
<h6>{{ .Email }}</h6>
//etc
</div>
显示注册服务商:
<div>
<p>Registrar</p>
<h6>{{ .RegistrarName }}</h6>
</div>
但是,这些都不起作用(我如何在一个字段中显示注册人名称,然后在另一个字段中显示技术名称?我显然是在浪费大量时间模板,而我对此的理解有些偏颇)。我已经阅读了所有我能读的东西,我试图将这些结构划分为多个单独的结构,等等。有人可以指出正确的方向并举一些例子吗?
谢谢!
答案 0 :(得分:1)
相对于当前上下文{{。}}评估模板字段。以下代码使用包含“ whois”作为键,res
作为值的映射来评估模板:
in.H{ "whois": res})
{{.whois}}
的值是您的结构,您可以从那里访问struc字段。因此,您可以这样做:
{{.whois.Registrant.Name}}