【发布时间】:2017-07-19 01:45:19
【问题描述】:
我试图覆盖一个结构列表,其中包含 2 个结构。我在结构中正确填充数据没有问题,问题是当我尝试将它呈现到 HTML 中时。我无法显示任何内容。
这是我的第一个 go web 项目,我正在开发一个为小型企业销售汽车的网站。我的数据库设计为 1..M 的 Cars to Pics。所以在汽车主页上。我只想加载一张包含汽车细节的图片。我尝试为此使用地图,但是当我只想打印一张图片以在通用 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)
}
在我传入结构之前的打印语句以我想要的方式为我提供了信息。
[{{20 2009 Honda Accord 5000} {20 public/pics/questionMark.jpg}} {{21 2009 Acura TLX 14000} {21 public/pics/kia.png}} {{22 2015 Kia Sportage 34000} {22 public/pics/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。