1

我正在使用confd通过模板填充文件。

在这个文件中,我想要一个移动和插入的元素列表。此切片包含字符串,如

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

(实际上,它是我使用splitconfd 函数拆分的字符串)。我希望,在每个容器上,能够过滤出容器名称并将列表移动到我的容器首先出现之后的那些。

举个例子,container-2我想得到结果

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

如何在 confd go 模板中做到这一点?我想我知道如何在 go 中做到这一点(但我在那种特定语言中不是那么好),但我不知道如何只使用模板来做到这一点......

4

1 回答 1

1

如果您无法在模板外部操作切片/字符串,并且如果您无法向模板添加自定义函数,您将不得不在模板内部执行此操作。它更冗长,但可行。

一种方法是将两个循环嵌套在父循环内。父级将查找您要遗漏的容器,此时它将生成两个子循环,并$i保存要遗漏的那个的索引。然后第一个子循环可以列出索引大于$i的容器,第二个子循环将列出索引小于的容器$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

于 2017-11-15T16:43:02.217 回答