go - 使用范围遍历 map ,只迭代一次

标签 go

我只需要在我的 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/

相关文章:

Go 版本 1.17.6 对于该版本的 Delve 来说太旧了(最低支持版本 1.18,使用 --check-go-version=false 抑制此错误)

go - 混合字段 :value and value initializers

http - 如果 http ://is missing,使用 url.ResolveReference() 解析错误的 URL

go - 为什么 Go 生成的 protobuf 文件包含互斥锁?

go - 如何使用 golang 设置 protobuf2 枚举

javascript - 使用 websockets Golang 将更改推送到客户端

go - 返回返回类型匹配接口(interface)的回调时出错

go - 如何清除 close-on-exec 标志?

go - 如何制作可变类型 slice

json - 在 Go 中循环嵌套的 JSON 元素