-
Notifications
You must be signed in to change notification settings - Fork 17.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
text/template: Methods vs funcs discrepancy #20503
Comments
I'm not experienced with the @bep, I think this is working as intended - even though from a user's point of view it's a bit unintuitive. Reading the package godoc:
Note that, in your example, both So, following the package's own godoc, it makes sense that You can also fix this by using So I would say this is not a bug in the sense that the package is not broken. You could argue that it could be made more user-friendly, but it could also lead to more complex rules. And it would probably warrant a proposal, not a bug report. |
It is a little confusing but yes it is working as intended. Use 'call'. |
Just in case other people are slow thinking as myself. I just figured out a workaround that is so obvious that I'm a little bit embarrassed showing it: My use case was/is: I had a map sent to the templates with some data that was rarely used, so I wanted to lazily load it without messing with the API (i.e. the map key/value range etc.). The workaround is, of course, to create a map type with methods: package main
import (
"bytes"
"fmt"
"text/template"
)
type MyMap map[string]interface{}
func (m MyMap) MyFunc() string {
f := m["func"].(func() string)
return f()
}
func main() {
m := make(MyMap)
m["func"] = func() string {
return "Hello"
}
tpl := "{{ .MyFunc }}"
var buf bytes.Buffer
tmpl, err := template.New("").Parse(tpl)
if err != nil {
panic(err)
}
if err := tmpl.Execute(&buf, m); err != nil {
panic(err)
}
fmt.Println(buf.String())
} The above example is a little bit constructed, but it shows the point, I hope. |
The following Go program:
Prints
This is, to me, unexpected behaviour. The
method
is invoked before it is ranged on, thefunc
not.The text was updated successfully, but these errors were encountered: