我需要在go模板中呈现嵌套的结构数据。我想知道是否可以用嵌套循环的方式在 .gohtml
模板文件.这是我的 .gohtml
代码。
<!DOCTYPE html>
<html>
<head>
<meta charser="utf-8" />
<title>Go templates</title>
</head>
<body>
<ul>
{{range $city := .}}
<li>
name: {{$city.name}}
hotels:
<ul>
{{range $hotel := $city.hotels}}
<li>
name: {{$hotel.name}}
address: {{$hotel.address}}
zip: {{$hotel.zip}}
</li>
{{end}}
</ul>
</li>
{{end}}
</ul>
</body>
</html>
这里是 main.go
代码。
package main
import (
"os"
"text/template"
)
var tpl *template.Template
func init() {
tpl = template.Must(template.New("").ParseGlob("./*.gohtml"))
}
func main() {
type hotel struct {
name string
address string
city string
zip int
}
type city struct {
name string
hotels []hotel
}
type region struct {
cities []city
}
hotel1 := hotel{
"Lambda",
"Street 19",
"Some city",
65530,
}
hotel2 := hotel{
"Black Sea",
"Street 21",
"Some city",
65543,
}
hotel3 := hotel{
"Blue Sea",
"Street 15",
"Some city",
54400,
}
hotel4 := hotel{
"Yellow Submarine",
"The Beatles Square",
"Some city",
54401,
}
hotel5 := hotel{
"LolKek",
"Cheburek",
"Some city",
14213,
}
city1 := city{
"Some city",
[]hotel{hotel1, hotel2},
}
city2 := city{
"Some city",
[]hotel{hotel3, hotel4},
}
city3 := city{
"Some city",
[]hotel{hotel5},
}
someRegion := region{
[]city{city1, city2, city3},
}
tpl.ExecuteTemplate(os.Stdout, "tpl.gohtml", someRegion)
}
终端上没有错误,当 go run main.go
但我不明白为什么输出是这样的?
<!DOCTYPE html>
<html>
<head>
<meta charser="utf-8" />
<title>Go templates</title>
</head>
<body>
<ul>
为什么会被切掉?
你没有看到任何错误,因为你没有检查错误,你省略了它们。
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
}
在做了这些修改之后,它就可以工作了,并且可以输出了(试试 去游乐场):
<!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>