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 關注
- 552 瀏覽
添加回答
舉報