在go模板中获取迭代器索引(consul-template)

问题描述 投票:1回答:1

我正在尝试获取一个简单的索引,我可以使用consul-template附加到Go模板片段的输出。看了一下,无法找出简单的解决方案。基本上,给出这个输入

backend web_back
    balance roundrobin
    {{range service "web-busybox" "passing"}}
        server  {{ .Name }} {{ .Address }}:80 check
    {{ end }}

我想看看web-busybox-n 10.1.1.1:80 check

其中n是范围循环中的当前索引。这可能是范围和地图吗?

loops dictionary go go-templates consul-template
1个回答
0
投票

在地图上进行测距时(没有值和可选键),没有迭代编号。您可以使用自定义功能实现所需。

一种可能的解决方案,使用inc()函数在每次迭代中递增索引变量:

func main() {
    t := template.Must(template.New("").Funcs(template.FuncMap{
        "inc": func(i int) int { return i + 1 },
    }).Parse(src))

    m := map[string]string{
        "one":   "first",
        "two":   "second",
        "three": "third",
    }

    fmt.Println(t.Execute(os.Stdout, m))
}

const src = `{{$idx := 0}}
{{range $key, $value := .}}
    index: {{$idx}} key: {{ $key }} value: {{ $value }}
    {{$idx = (inc $idx)}}
{{end}}`

这输出(在Go Payground上试试)(压缩输出):

index: 0 key: one value: first
index: 1 key: three value: third
index: 2 key: two value: second

查看类似/相关问题:

Go template remove the last comma in range loop

Join range block in go template

Golang code to repeat an html code n times

© www.soinside.com 2019 - 2024. All rights reserved.