我有以下情况,我将包含映射的结构传递给模板:
package main
import (
"log"
"os"
"text/template"
)
var fns = template.FuncMap{
"plus1": func(x int) int {
return x + 1
},
}
type codec struct {
Names map[string]string
Count int
}
func main() {
a := map[string]string{"one": "1",
"two": "2",
"three": "3"}
t := template.Must(template.New("abc").Funcs(fns).Parse(`{{$l := len .Names}}{{range $k, $v := .Names}}{{if ne (plus1 $.Count) $l}}{{$k}} {{$v}} {{end}}{{end}}.`))
err := t.Execute(os.Stdout, codec{a, 0})
if err != nil {
log.Println(err)
}
}
我想增加 codec
的 Count
字段,这样我就可以知道我看到了多少个 map 项。
最佳答案
一个解决方案是使 plus1
函数成为一个直接作用于 codec
值的闭包:
// first create a codec instance
c := codec {a, 0}
// now define the function as a closure with a reference to c
fns := template.FuncMap{
"plus1": func() int {
c.Count++
return c.Count
},
}
// now we don't need to pass anything to it in the template
t := template.Must(template.New("abc").Funcs(fns).Parse(`{{$l := len .Names}}{{range $k, $v := .Names}}{{if ne (plus1) $l}}{{$k}} {{$v}} {{end}}{{end}}.`))
输出是:
one 1 three 3
我猜你的目标是什么?并在执行结束时将该值保留在c
中。
关于templates - 如何更新 Go 模板中的字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35034039/