dqrzot2791 2019-04-17 19:10
浏览 85

在Go模板中获取迭代器索引(领事模板)

I'm trying to get a simple index that I can append to output of a Go template snippet using consul-template. Looked around a bit and couldn't figure out the simple solution. Basically, given this input

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

I would like to see web-busybox-n 10.1.1.1:80 check

Where n is the current index in the range loop. Is this possible with range and maps?

  • 写回答

2条回答 默认 最新

  • dongqu9917 2019-04-17 20:12
    关注

    There is no iteration number when ranging over maps (only a value and an optional key). You can achieve what you want with custom functions.

    One possible solution that uses an inc() function to increment an index variable in each iteration:

    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}}`
    

    This outputs (try it on the Go Payground) (compacted output):

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

    See similar / related questions:

    Go template remove the last comma in range loop

    Join range block in go template

    Golang code to repeat an html code n times

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c