Skip to content

proposal: text/template: make "template" action accept dynamic name as argument #33449

@a8m

Description

@a8m

Proposal

I'm suggesting to change the template action in text/template to accept "dynamic parameter" for its name; behave like a function that accepts 2 arguments. For example:

{{range $_, $p := .Templates}}
  {{$tmpl := printf "path/to/%s" $p.Name}}
  {{template $tmpl $}}
{{end}} 

The current solution for doing this, is to do something as described in StackOverflow:

tmpl := template.New("main")
tmpl.Funcs(template.FuncMap{
    "xtemplate": func(name string, v interface{}) (string, error) {
        var buf bytes.Buffer
        if err := tmpl.ExecuteTemplate(&buf, name, v); err != nil {
            return "", err
        }
        return buf.String(), nil
    },
})

I already hacked yesterday and added it to both the parser and the evaluator (exec.go), but I need to prettify it a bit, add proper tests and docs, and then I can make a CL (if it won't be rejected too quickly). It will be easier to consider this proposal when you see the additional complexity that comes with it.

Backward compatibility

This change doesn't break the compatibility promise of Go, but it requires to either add additional field to parse.TemplateNode or use parse.TemplateNode.Pipe for holding the template-name argument.
We can't change the type of parse.TemplateNode.Name, which is string.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions