我正在嘗試範圍內包含2個結構的結構列表。我沒有問題在結構中正確填充數據,問題是當我嘗試將其呈現到HTML中時。我無法顯示任何內容。轉到模板結構的結構的範圍
這是我第一次參加web項目,我正在網站上爲小企業出售汽車。我的數據庫被設計爲1..M的Cars to Pics。所以在主頁上。我想只加載1張圖片的車的細節。我試圖使用地圖,但我遇到了一個問題,當我想打印出只有1張照片時,需要使用公共ID上正確的車輛詳細信息。所以我想通過使用第三個結構體,我爲每個ID抽出一張圖片就行了。
type Car struct {
Id int
Year, Make, Model, Price string
}
type Pics struct {
Id int
Path string
}
type CarDetail struct {
Cars Car
Pic Pics
}
func cars(w http.ResponseWriter, r *http.Request){
//loads all the cars in the database
cars := loadCars()
carDetails := make([]CarDetail,0)
carIds := make([]int,len(cars))
for i := 0; i < len(cars); i++{
//gets all the car IDs in the db
carIds[i] = getCarID(cars[i])
photoPath := loadSinglePhoto(carIds[i]) //now have the single photo
n := CarDetail{Cars:cars[i],Pic:photoPath}
carDetails = append(carDetails, n)
}
fmt.Println(carDetails) //getting car details the way I want
tpl.ExecuteTemplate(w, "cars", &carDetails)
}
就在我傳入結構之前的print語句給我提供了我想要的信息。
[{20 2009年本田雅閣5000} {20 public/pics/questionMark.jpg}} {{21 2009 Acura TLX 14000} {21 2015 Kia Sportage 34000 } {22公/圖片/ kia.png}}]
現在,當我試圖使其在HTML
{{range .}}
<h3>{{.Cars.Make}} - {{.Cars.Model}} - {{.Cars.Year}}</h3>
<img src="{{.Pic.Path}}" id="{{.Pic.Id}}">
{{end}}
,歡迎隨時與我的關鍵代碼或暗示的另一種方式。先謝謝你!
*總是*檢查'ExecuteTemplate'返回的'error'。 'cars'應該是模板名稱而不是變量名稱。可以使用'tpl.Execute(w,&carsDetail)'來代替'ExecuteTemplate'。 – putu