How to return unique elements in an array using Go's text/template package? -
i new go , struggling trying figure out way homecoming unique variables array in go templating language. configure software , not have access source alter actual programme template.
i have knocked illustration in 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}}\n{{end}}") if err != nil { panic(err) } err = tmpl.execute(os.stdout, arr) if err != nil { panic(err) } }
right returns:
the thing is: mice thing is: mice thing is: mice thing is: mice thing is: mice thing is: mice thing is: mice thing is: toad thing is: toad thing is: mice
what trying craft template input array filters duplicates , returns:
the thing is: mice thing is: toad
i stuck know virtually no go , struggle find array manipulation methods in docs. 1 have tips?
addeniumsorry not beingness clear wrote question on bus on way work.
i don't have access go code outside template. have template can edit , within template have array may or may not have multiple values , need print them once.
i appreciate not how templates meant work if there dirty way save me several days work.
you can create own functions 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}}\n{{end}}")
where unique
defined as:
func unique(e []string) []string { r := []string{} _, s := range e { if !contains(r[:], s) { r = append(r, s) } } homecoming r } func contains(e []string, c string) bool { _, s := range e { if s == c { homecoming true } } homecoming false }
output:
the thing is: mice thing is: toad
(it might improve utilize map
.. gives basic idea)
that said - have considered filtering outside of template? create things nicer you.. can iterate on actual piece within template.
working sample: https://play.golang.org/p/l_8t10cphw
go
No comments:
Post a Comment