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: builtins FuncMap is not used unless Parse
is called
#56571
Comments
Based on your example, you want to call the parser directly. You can tell the parser to not complain about functions by, after the call to Closing because I don't think there is anything to change in the text/template package. Please comment if you disagree. |
Hi @ianlancetaylor, the issue doesn't lie in the parser. The issue is declaring a new template via In scenarios where you're using I hope that makes more sense. I don't believe this issue should be closed |
In that case, could you show a test case that demonstrates the problem? The test case you showed earlier doesn't use |
Sure, here's the code from the playground link in the OP: package main
import (
"bytes"
"text/template"
"text/template/parse"
)
func main() {
tmpl := `
{{ define "base" }}
{{ if eq "true" "true" }}
{{ end }}
{{ end }}
`
parser := parse.New("base")
treeSet := make(map[string]*parse.Tree)
_, err := parser.Parse(tmpl, "{{", "}}", treeSet)
if err != nil {
panic(err)
}
t := template.New("base")
for k, v := range treeSet {
_, err := t.AddParseTree(k, v)
if err != nil {
panic(err)
}
}
buf := bytes.Buffer{}
err = t.ExecuteTemplate(&buf, "base", nil)
if err != nil {
panic(err) // panic here: function "eq" not defined
}
} See the go/src/text/template/template.go Line 210 in a343f40
But what if you use Line 39 in a343f40
Perhaps we could move the addition of go/src/text/template/template.go Line 70 in a343f40
On line 77: Without this, theres not much utility to |
I saw the code in the playground link. When I run it I see a panic after a call to |
What version of Go are you using (
go version
)?1.18.5
Does this issue reproduce with the latest release?
Yes
What operating system and processor architecture are you using (
go env
)?What did you do?
https://go.dev/play/p/nsZQiC5SVB6
What did you expect to see?
The builtins FuncMap should be applied when calling template.New()
What did you see instead?
panic: template: base:3: function "eq" not defined
In my program I would like to memoize parsed templates as
parse.Tree
objects so that they can be applied to templates later. An alternative approach would be to keep the instance oftemplate.Template
around but doing so maintains references to the functions that are passed to it, which is undesirable.I propose that the
builtins
function map be applied to the template as soon asNew
is called and the internalinit
method executes.I'm happy to contribute the change if this behavior is deemed unintended 😁
The text was updated successfully, but these errors were encountered: