编码器。我需要在 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},
}
为什么会被剪掉?
白板的微信
相关分类