I've looked through online examples and other splice examples, but haven't succeeded.
Here's my HTML
<table style="width:100%">
<tr>
<th>Source</th>
<th>Title</th>
<th>Author</th>
<th>URL</th>
</tr>
{{range .Arts}}
<tr>
<td>{{ .Source }}</td>
<td>{{ .Title }}</td>
<td>{{ .Author }}</td>
<td>{{ .URL }}</td>
</tr>
{{end}}
</table>
GO:
Source string
Author string
Title string
URL string
}
type NewsPage struct {
Header string
News string
Articles []Article
}
var Arts []Article
func newsDisplayHandler(w http.ResponseWriter, r *http.Request) {
// temp := template.Must(template.ParseFiles("layout.html"))
newsPage := NewsPage{
Header: "This is your Mostly Fake news update for " + time.Now().Format("Mon 2006-01-2"),
News: "Here's your daily dose of mostly Fake News",
Articles: Arts}
parse, _ := template.ParseFiles("newsPage.html")
parse.Execute(w, newsPage)
// temp.Execute(w, newsPage)
}
What am I missing? The rest of my code works and is not the issue here. My issues is that I am not able to loop through my slice to add it to the HTML table. I wont know the number of Articles at run time, as I'm getting the info from an API.
From the code you provided, the array is empty and as the documentation reads:
If the value of the pipeline has length zero, nothing is output;
Your HTML looks fine.
You're also never passing the array:
try:
newsPage := NewsPage{
Arts: Arts
}
instead of
newsPage := NewsPage{
Articles: Arts
}