Golang如何为嵌套结构创建模板?
我正在尝试将JSON响应模板化到前端,我当前的结构是:Golang如何为嵌套结构创建模板?,go,go-gin,Go,Go Gin,我正在尝试将JSON响应模板化到前端,我当前的结构是: type Response struct { WhoisRecord struct { CreatedDate time.Time `json:"createdDate"` UpdatedDate time.Time `json:"updatedDate"` ExpiresDate time.Time `json:"expire
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)
但这就是我遇到问题的地方,代码可以工作,但我不确定如何对它进行模板化,因为它是嵌套的
例如,我想在单独的表中显示注册人、管理和技术联系人详细信息(返回的所有字段)。同时显示创建、更新和过期日期。然后通过显示注册器、IP和名称服务器(在本例中为名称服务器下的主机名
字段)来完成
我将如何在我的家庭作业.html文件中提供这些内容?我什么都试过了。通常我会做一些事情,比如:
要显示IP,请执行以下操作:
{{range.Ips}
知识产权
{{ . }}
{{end}
要显示寄存器数据,请执行以下操作:
<div>
<p>Name</p>
<h6>{{ .Name }}</h6>
<p>Email</p>
<h6>{{ .Email }}</h6>
//etc
</div>
名字
{{.Name}
电子邮件
{{.Email}
//等
要显示注册官:
<div>
<p>Registrar</p>
<h6>{{ .RegistrarName }}</h6>
</div>
登记员
{{.registerName}
但这一切都不起作用(我如何在一个字段中显示注册人姓名,然后在另一个字段中显示技术名称?我显然把模板弄得一团糟,我对它的理解有点偏颇)。我已经读了所有我能读的东西,我试着划分结构并作为单独的结构使用,等等。什么都不起作用。有人能给我指出正确的方向并举例说明吗
谢谢 模板字段相对于当前上下文{{.}进行计算。下面使用包含“whois”作为键的映射,以及res
作为值的映射来评估模板:
in.H{ "whois": res})
{{.whois}}
的值是您的结构,您可以从那里访问struc字段。因此,您可以:
{{.whois.Registrant.Name}}
请尝试{range.whois.Ips}
@BurakSerdar,这是有效的,但是如何访问其他深度嵌套的JSON?这也是由于另一个错误造成的,但至少在某种程度上是可行的。虽然我修复了另一个,但我仍然想知道如何访问深层嵌套结构,并了解发生了什么事情您正在访问结构字段,而不是json。该结构放在一个名为“whois”的变量中,因此您可以从中使用点符号:.whois.Registrant.Name,etc@BurakSerdar你的回答救了我!你能提交它吗?这样我就可以标记为解决方案了?
in.H{ "whois": res})
{{.whois.Registrant.Name}}