1 回答
TA贡献1883条经验 获得超3个赞
您看不到任何错误,因为您没有检查错误,而是忽略了它们。
Template.ExecuteTemplate()返回错误,请检查它:
if err := tpl.ExecuteTemplate(os.Stdout, "tpl.gohtml", someRegion); err != nil {
fmt.Println(err)
}
这将输出:
template: :9:29: executing "" at <.>: range can't iterate over {[{Some city [{Lambda Street 19 Some city 65530} {Black Sea Street 21 Some city 65543}]} {Some city [{Blue Sea Street 15 Some city 54400} {Yellow Submarine The Beatles Square Some city 54401}]} {Some city [{LolKek Cheburek Some city 14213}]}]}
错误很明显:你传递了一个结构来执行,然后你尝试在它上面进行范围。你不能。切片上的范围:
{{range $city := .cities}}
这当然行不通:您必须导出结构字段才能在模板中访问它。
type region struct {
Cities []city
}
在模板中:
{{range $city := .Cities}}
您还必须导出其他结构字段:
type hotel struct {
Name string
Address string
City string
Zip int
}
type city struct {
Name string
Hotels []hotel
}
在这些更改之后,它将工作并输出(在Go Playground上尝试):
<!DOCTYPE html>
<html>
<head>
<meta charser="utf-8" />
<title>Go templates</title>
</head>
<body>
<ul>
<li>
name: Some city
hotels:
<ul>
<li>
name: Lambda
address: Street 19
zip: 65530
</li>
<li>
name: Black Sea
address: Street 21
zip: 65543
</li>
</ul>
</li>
<li>
name: Some city
hotels:
<ul>
<li>
name: Blue Sea
address: Street 15
zip: 54400
</li>
<li>
name: Yellow Submarine
address: The Beatles Square
zip: 54401
</li>
</ul>
</li>
<li>
name: Some city
hotels:
<ul>
<li>
name: LolKek
address: Cheburek
zip: 14213
</li>
</ul>
</li>
</ul>
</body>
</html>
- 1 回答
- 0 关注
- 530 浏览
添加回答
举报