dreamy1992 2017-11-14 14:19
浏览 168
已采纳

如何在go模板中移动切片?

I'm using confd to populate a file through a template.

In this file, I want to have a list of elements shifted and inserted. This slice contains strings like

0=container-1
1=container-2
2=container-3
3=container-4

(in fact, it is a string that I split using split confd function). I want, on each container, be able to filter container name out and shift the list to have the ones after my container appear first.

As an example, on container-2 I would like to have as result

2=container-3
3=container-4
0=container-1

How to do that in a confd go template ? I think I know how to do that in go (but I'm not that good in that particular language), but I don't find how to do that using only a template ...

  • 写回答

1条回答 默认 最新

  • drl2051 2017-11-15 16:43
    关注

    If you are unable to manipulate the slice/string outside the template, and if you are unable to add custom functions to the template either you will have do this inside the template. It's more verbose, but doable.

    One approach is to have two loops nested inside a parent loop. The parent will look for the container you want to leave out, at which point it will spawn the two child loops with $i holding the index of the one to be left out. The first child loop can then list containers whose index is greater than $i and the second child loop will list containers whose index is less than $i.

    {{range $i, $c := $cons}}
        {{/* find item to be skipped */}}
        {{if (eq $c $.Skip)}}
    
            {{range $j, $c := $cons}}
                {{/* list items that come after the one to be skipped */}}
                {{if (gt $j $i)}}
                    {{$c}}
                {{end}}
            {{end}}
    
            {{range $j, $c := $cons}}
                {{/* list items that come before the one to be skipped */}}
                {{if (lt $j $i)}}
                    {{$c}}
                {{end}}
            {{end}}
    
        {{end}}
    {{end}}
    

    https://play.golang.org/p/lGdExfHAvy

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题