Dereferencing pointers in golang text / template

Inside the golang template, with a simple derivation of values, it seems that pointers are automatically dereferenced. When .ID is a pointer to an int ,

{{.ID}} outputs 5

But when I try to use it in the pipeline, {{if eq .ID 5}} , I get an error.

executing "mytemplate" at <eq .ID 5>: error calling eq: invalid type for comparison

How to make dereferencing a pointer inside a template pipeline?

+7
source share
1 answer

One way is to register a custom function that separates the pointer so that you can compare the result with what you want or something else with it.

For instance:

 func main() { t := template.Must(template.New("").Funcs(template.FuncMap{ "Deref": func(i *int) int { return *i }, }).Parse(src)) i := 5 m := map[string]interface{}{"ID": &i} if err := t.Execute(os.Stdout, m); err != nil { fmt.Println(err) } } const src = `{{if eq 5 (Deref .ID)}}It five.{{else}}Not five: {{.ID}}{{end}}` 

Output:

 It five. 

Alternatively, you can use another custom function that will take a pointer and not a pointer, and perform a comparison, for example:

  "Cmp": func(i *int, j int) bool { return *i == j }, 

And calling it from the template:

 {{if Cmp .ID 5}}It five.{{else}}Not five: {{.ID}}{{end}} 

The output is the same. Try them on the go playground .

+5
source

Source: https://habr.com/ru/post/1243780/


All Articles