I want to compare two templates in Go, the simplified example below get an unexpected result. How to compare them?
https://play.golang.org/p/Q3eAxVEzcFp
I have tried DeepEqual but it does not work.
package main
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"text/template"
)
// basicFunctions are the set of initial
// functions provided to every template.
var basicFunctions = template.FuncMap{
"json": func(v interface{}) string {
a, _ := json.Marshal(v)
return string(a)
},
"split": strings.Split,
"join": strings.Join,
"title": strings.Title,
"lower": strings.ToLower,
"upper": strings.ToUpper,
}
func main() {
t1, _ := template.New("").Funcs(basicFunctions).Parse("{{.ID}}")
t2, _ := template.New("").Funcs(basicFunctions).Parse("{{.ID}}")
fmt.Println(reflect.DeepEqual(t1, t2)) // want to be true, actually false
}
I want to get a true
answer.
Execute the two templates using the same data, but write each to a different buffer. Compare the bytes in the buffers. Repeat with different data until they diverge or you are satisfied that they are the same.
t1, _ := template.New("").Funcs(basicFunctions).Parse("{{.ID}}")
t2, _ := template.New("").Funcs(basicFunctions).Parse("{{.ID}}")
var b1, b2 bytes.Buffer
d := struct{ ID string }{ID: "test"}
t1.Execute(&b1, d)
t2.Execute(&b2, d)
fmt.Println(bytes.Equal(b1.Bytes(), b2.Bytes())) // true
https://play.golang.org/p/jz2Lbmf-4RY
There should be some set of data inputs that would satisfy you that these templates are the same, given that they output the same bytes given the same inputs.