登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-15 18:15:39 382浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《获取go模板中的迭代器索引(consul-template)》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

我正在尝试获取一个简单的索引,我可以使用 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

Join range block in go template

Golang code to repeat an html code n times

理论要掌握,实操不能落!以上关于《获取go模板中的迭代器索引(consul-template)》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>