【发布时间】:2020-09-15 22:26:10
【问题描述】:
编码员。
我需要在 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>
为什么会被剪掉?
【问题讨论】:
-
tpl.ExecuteTemplate(os.Stdout, "tpl.gohtml", someRegion) }返回的错误会指向问题所在。
标签: loops go struct slice go-templates