Go templates with eq and index

Ondra picture Ondra · Oct 22, 2015 · Viewed 16.4k times · Source

Go templates have some unexpected results when using eq with index for me. See this code:

package main

import (
    "os"
    "text/template"
)

func main() {
    const myTemplate = `
{{range $n := .}}
    {{index $n 0}} {{if (index $n 0) eq (index $n 1)}}={{else}}!={{end}} {{index $n 1}}
{{end}}
`
    t := template.Must(template.New("").Parse(myTemplate))

    t.Execute(os.Stdout,
        [][2]int{
            [2]int{1, 2},
            [2]int{2, 2},
            [2]int{4, 2},
        })

}

I expect to have output

1 != 2
2 = 2
4 != 2

but I get

1 = 2
2 = 2
4 = 2

What should I change to be able to compare array members in go templates?

Answer

Ainar-G picture Ainar-G · Oct 22, 2015

eq is a prefix operation:

{{if eq (index $n 0) (index $n 1)}}={{else}}!={{end}}

Playground: http://play.golang.org/p/KEfXH6s7N1.