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 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误