Home > front end >  Parameter to Go custom template function
Parameter to Go custom template function

Time:09-26

Please take a look at https://play.golang.org/p/EbWA15toVa9

in which I

  • define func iterate(count int) []int on line 25
  • call it with iterate 5 on line 15

That's all OK, but, when call it with iterate (printf "%d" 3) on line 20, I got the error of:

template: t:12:39: executing "t" at <3>: wrong type for value; expected int; got string

Wouldn't the (printf "%d" 3) get executed first and when passed to iterate, it'll become iterate 3? Why the above error instead?

Full code enclosed:

package main

import (
    "log"
    "os"
    "text/template"
)

var x = `{{define "t1"}}
{{- index . 0}} {{index . 1}} {{index . 2}} {{index . 3}}
{{end -}}

hello, {{template "t1" args . 543 false 0.1234}}

{{- range $val := iterate 5 }}
  {{ $val }}
{{- end }}
{{ (printf "%d" 3) }}

{{- range $val := iterate (printf "%d" 3) }}
  {{ $val }}
{{- end }}
`

func iterate(count int) []int {
    var i int
    var Items []int
    for i = 0; i < (count); i   {
        Items = append(Items, i)
    }
    return Items
}

func args(vs ...interface{}) []interface{} { return vs }

func main() {
    t := template.Must(template.New("t").Funcs(template.FuncMap{"args": args, "iterate": iterate}).Parse(x))
    err := t.Execute(os.Stdout, "foobar")
    if err != nil {
        log.Fatal(err)
    }
}

CodePudding user response:

You are correct that the printf “%d” 3 gets evaluated first. The problem seems to be that printf “%d” 3 produces a string, but your iterate function has an argument of type int. The string will not be converted.

  • Related