我只需要在我的 golang 模板中迭代一次循环,目前它正在遍历所有键,但我希望它在一次迭代后停止。
我该怎么做?
{{range .Users}}
<div>
{{.Name}}
</div>
{{end}}
最佳答案
两种解决方案;循环时检查您的索引是否为 0:
{{range $index, $element := . }}{{if eq $index 0 -}}
Item: {{$element}}
{{end}}{{end -}}
或者您可以定义一个“第一个”函数,它接受一个 slice 并将其截断为长度 1。
{{range first .}}
Item: {{.}}
{{end}}
这是演示两者的完整代码,您也可以 try on the playground.
package main
import (
"fmt"
"os"
"text/template"
)
var t = template.Must(template.New("x").Parse(
"[{{range $index, $element := . }}{{if eq $index 0 -}}{{$element}}{{end}}{{end -}}]"))
var funcs = map[string]interface{}{
"first": func(arg []string) []string {
if len(arg) > 0 {
return arg[:1]
}
return nil
},
}
var t2 = template.Must(template.New("x").Funcs(funcs).Parse(
"[{{range first . }}{{.}}{{end -}}]"))
func main() {
tmpls := []*template.Template{t, t2}
for i, t := range tmpls {
fmt.Println("TEMPLATE", i)
a := []string{"one", "two", "three"}
for j := 0; j < len(a); j++ {
fmt.Println("with input slice of length", j)
t.Execute(os.Stdout, a[:j])
fmt.Println()
}
fmt.Println()
}
}
关于go - 使用范围遍历 map ,只迭代一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37777869/