我正在尝试获取一个简单的索引,我可以使用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是范围循环中的当前索引。这可能是范围和地图吗?
在地图上进行测距时(没有值和可选键),没有迭代编号。您可以使用自定义功能实现所需。
一种可能的解决方案,使用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