dougou7782 2014-11-11 21:29
浏览 170
已采纳

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

I am new to Go and I am struggling trying to figure out a way to return unique variables from an array in Go templating language. This is to configure some software and I do not have access to the source to change the actual program only the template.

I have knocked up an example in the Go playground:

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}}
{{end}}")
      if err != nil { panic(err) }
      err = tmpl.Execute(os.Stdout, arr)
      if err != nil { panic(err) }

}

Right now this returns:

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

What I am trying to do is craft a template that from the input array filters duplicates and only returns:

The thing is: mice
The thing is: toad

I am really stuck as I know virtually no go and struggle to find any array manipulation methods in the docs. Any one have any tips?

Addenium

Sorry for not being clear I wrote this question on the bus on the way to work.

I don't have access to any go code outside the template. I have a template I can edit and within that template I have an array that may or may not have multiple values and I need to print them once.

I appreciate this is not how templates are meant to work but if there is some dirty way to do this it would save me several days work.

  • 写回答

2条回答 默认 最新

  • dongzhina7098 2014-11-11 21:57
    关注

    You can create your own functions for the template via 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}}
    {{end}}")
    

    Where unique is defined as:

    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
    }
    

    Output:

    The thing is: mice
    The thing is: toad
    

    (It might be better to use a map .. but this gives you the basic idea)

    That said - have you considered filtering this outside of the template? That would make things nicer for you.. then you can just iterate over the actual slice within the template.

    Working sample: https://play.golang.org/p/L_8t10CpHW

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助