如何使用 Go 的 text/template 包返回数组中的唯一元素?

ric*_*ard 4 go

我是 Go 新手,我正在努力寻找一种从 Go 模板语言中的数组返回唯一变量的方法。这是为了配置一些软件,我无法访问源代码来更改实际程序,只能更改模板。

我在 Go 操场上举了一个例子:

https://play.golang.org/

package main

import "os"
import "text/template"

func main() {

      var arr [10]string
      arr[0]="mice"
      arr[1]="mice"
      arr[2]="mice"
      arr[3]="mice"
      arr[4]="mice"
      arr[5]="mice"
      arr[6]="mice"
      arr[7]="toad"
      arr[8]="toad"
      arr[9]="mice"

      tmpl, err := template.New("test").Parse("{{range $index, $thing := $}}The thing is: {{$thing}}\n{{end}}")
      if err != nil { panic(err) }
      err = tmpl.Execute(os.Stdout, arr)
      if err != nil { panic(err) }

}
Run Code Online (Sandbox Code Playgroud)

现在返回:

The thing is: mice
The thing is: mice
The thing is: mice
The thing is: mice
The thing is: mice
The thing is: mice
The thing is: mice
The thing is: toad
The thing is: toad
The thing is: mice
Run Code Online (Sandbox Code Playgroud)

我想做的是制作一个模板,该模板从输入数组过滤器重复并仅返回:

The thing is: mice
The thing is: toad
Run Code Online (Sandbox Code Playgroud)

我真的很困惑,因为我几乎不知道如何去并且很难在文档中找到任何数组操作方法。有人有什么建议吗?

附录

抱歉,我不太清楚,我是在上班的公交车上写下这个问题的。

我无权访问模板之外的任何 go 代码。我有一个可以编辑的模板,在该模板中我有一个数组,可能有也可能没有多个值,我需要将它们打印一次。

我明白这不是模板的工作方式,但如果有一些肮脏的方法来做到这一点,它会节省我几天的工作。

Sim*_*ead 5

您可以通过以下方式为模板创建自己的函数template.FuncMap

arr := []string{
    "mice",
    "mice",
    "mice",
    "mice",
    "mice",
    "mice",
    "mice",
    "toad",
    "toad",
    "mice",
}

customFunctions := template.FuncMap{"unique" : unique}

tmpl, err := template.New("test").Funcs(customFunctions).Parse("{{range $index, $thing := unique $}}The thing is: {{$thing}}\n{{end}}")
Run Code Online (Sandbox Code Playgroud)

其中unique定义为:

func unique(e []string) []string {
    r := []string{}

    for _, s := range e {
        if !contains(r[:], s) {
            r = append(r, s)
        }
    }
    return r
}

func contains(e []string, c string) bool {
    for _, s := range e {
        if s == c {
            return true
        }
    }
    return false
}
Run Code Online (Sandbox Code Playgroud)

输出:

The thing is: mice
The thing is: toad
Run Code Online (Sandbox Code Playgroud)

(使用map.. 可能会更好,但这给了你基本的想法)

也就是说,您是否考虑过在模板之外过滤此内容?这会让事情变得更好......然后你可以迭代模板中的实际切片。

工作示例: https: //play.golang.org/p/L_8t10CpHW