How can I send the result of named-template to a function

1/24/2019

I am trying to indent the result of a named-template. I have tried all of below syntax. Parentheses around "template name ." do not work either.

{{template "my-org.labels" . | indent 8}}
{{indent 8 template "mbfs-postgres.labels" .}}
{{with template "mbfs-postgres.labels" .}}...
-- Paddy
go
go-templates
kubernetes-helm

1 Answer

1/24/2019

There is not built-in support for sending the results of a template to a function.

It is possible to write a template function to do this: The execTemplate function returns a function that executes a named template in t.

func execTemplate(t *template.Template) func(string, interface{}) (string, error) {
    return func(name string, v interface{}) (string, error) {
        var buf strings.Builder
        err := t.ExecuteTemplate(&buf, name, v)
        return buf.String(), err
    }
}

Use it like this:

    t := template.New("")
    t = template.Must(t.Funcs(template.FuncMap{"exec": execTemplate(t), "inent": indent}).Parse(`
The template is: {{exec "labels" . | indent 8}}
{{define "labels"}}Hello from Labels!{{end}}`))
    t.Execute(os.Stdout, nil)

There are variations on this basic idea that may or may not be more convenient to use. For example, a value can be passed as an argument to the template instead of using a template function.

type execTemplate struct {
    t *template.Template
}

func (et execTemplate) Execute(name string, v interface{}) (string, error) {
    var buf strings.Builder
    err := et.t.ExecuteTemplate(&buf, name, v)
    return buf.String(), err
}

t := template.Must(template.New("").Funcs(template.FuncMap{"indent": 
indent}).Parse(`The template is: {{.Execute "labels" . | indent 8}}
   {{define "labels"}}Hello from Labels!{{end}}`))
fmt.Println(t.Execute(os.Stdout, execTemplate{t}))
-- Cerise Limón
Source: StackOverflow