英文:
Display a count on html template in Go
问题
使用Go中的html/templates,您可以执行以下操作:
<table class="table table-striped table-hover" id="todolist">
{{$i:=1}}
{{range .}}
<tr>
<td><a href="id/{{.Id}}">{{$i}}</a></td>
<td>{{.Title}}</td>
<td>{{.Description}}</td>
</tr>
{{$i++}}
{{end}}
</table>
英文:
Using html/templates in Go can you do the following:
<table class="table table-striped table-hover" id="todolist">
{{$i:=1}}
{{range .}}
<tr>
<td><a href="id/{{.Id}}">{{$i}}</a></td>
<td>{{.Title}}</td>
<td>{{.Description}}</td>
</tr>
{{$i++}}
{{end}}
</table>
every time I add the $i variable the app crashes.
答案1
得分: 17
<table class="table table-striped table-hover" id="todolist">
{{range $index, $results := .}}
<tr>
<td>{{add $index 1}}</td>
<td>{{.Title}}</td>
<td>{{.Description}}</td>
</tr>
{{end}}
</table>
func add(x, y int) int {
return x + y
}
type ToDo struct {
Id int
Title string
Description string
}
func IndexHandler(writer http.ResponseWriter, request *http.Request) {
results := []ToDo{ToDo{5323, "foo", "bar"}, ToDo{632, "foo", "bar"}}
funcs := template.FuncMap{"add": add}
temp := template.Must(template.New("index.html").Funcs(funcs).ParseFiles(templateDir + "/index.html"))
temp.Execute(writer, results)
}
英文:
In my html template:
<table class="table table-striped table-hover" id="todolist">
{{range $index, $results := .}}
<tr>
<td>{{add $index 1}}</td>
<td>{{.Title}}</td>
<td>{{.Description}}</td>
</tr>
{{end}}
</table>
In the go code I wrote a function which I passed to the FuncMap:
func add(x, y int) int {
return x + y
}
In my handler:
type ToDo struct {
Id int
Title string
Description string
}
func IndexHandler(writer http.ResponseWriter, request *http.Request) {
results := []ToDo{ToDo{5323, "foo", "bar"}, ToDo{632, "foo", "bar"}}
funcs := template.FuncMap{"add": add}
temp := template.Must(template.New("index.html").Funcs(funcs).ParseFiles(templateDir + "/index.html"))
temp.Execute(writer, results)
}
答案2
得分: 9
查看text/template
的Variables
部分
http://golang.org/pkg/text/template/
range $index, $element := pipeline
英文:
Check out the Variables
section of text/template
http://golang.org/pkg/text/template/
range $index, $element := pipeline
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论