gpt4 book ai didi

templates - 在 Go 中显示 html 模板的计数

转载 作者:IT王子 更新时间:2023-10-29 01:10:19 25 4
gpt4 key购买 nike

在 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>

每次我添加 $i 变量时,应用程序都会崩溃。

最佳答案

在我的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>

在 go 代码中,我编写了一个传递给 FuncMap 的函数:

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)
}

关于templates - 在 Go 中显示 html 模板的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14102845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com