I have 34 products in a CSV file and I want to use each of them in an HTML file. For this purpose, I need an array key so that I can use a value in an HTML file one by one.
Problem
- Whenever I execute this code, it prints only the last product name.
- I don't know how to make an array in a struct so that I can use it as a key using the for-loop.
Code
type List struct {
ProductsList string
}
func Home(w http.ResponseWriter, r *http.Request) {
var user List
for i := 0; i < 34; i {
user = List{
ProductsList: products.AccessData(i),
}
}
HomeTmpl.Execute(w, user)
}
CodePudding user response:
We can make ProductsList
a slice(fancy array) by delaring it like this []string
. We can then use the append
function to add elements to the end of the slice. This will make a slice where the index of the slice matches i
.
type List struct {
ProductsList []string
}
func Home(w http.ResponseWriter, r *http.Request) {
var user List
for i := 0; i < 34; i {
user.ProductsList = append(user.ProductsList, products.AccessData(i))
}
HomeTmpl.Execute(w, user)
}
CodePudding user response:
Try this bro
I change ProductList properties to slice string
type List struct {
ProductsList []string
}
func Home(w http.ResponseWriter, r *http.Request) {
AllData := []string{}
for i := 0; i < 34; i {
append(AllData, products.AccessData(i))
}
user := List{ ProductsList: AllData }
// user.ProducList = ["yourdata","hello","example","and more"]
HomeTmpl.Execute(w, user)
}