get the value of a go template from inside another

2019-08-31 05:50发布

This question already has an answer here:

I have two templates T1 and T2. I want to get the output of T1 and do a some extra processing on it inside T2. My question is:

how do I store the output of T1 in a variable inside T2? Is this even possible?

Here's some pseudo-template:

{{define "T1"}}
    {{ printf "%s-%s" complex stuff }}
{{end}}
{{define "T2"}}
    {{ $some_var := output_from_template "T1"}}  <<<<<<<<<<<
    {{ etc }}
{{end}}

1条回答
Evening l夕情丶
2楼-- · 2019-08-31 05:51

There is no builtin support for storing the result of a template in a template variable, only for the inclusion of the result.

But you can register custom functions with any complex functionality you want. You may register a GetOutput function which would execute a template identified by its name, and it could return the result as a string, which you can store in a template variable.

Example doing this:

func main() {
    t := template.New("")

    t = template.Must(t.Funcs(template.FuncMap{
        "GetOutput": func(name string) (string, error) {
            buf := &bytes.Buffer{}
            err := t.ExecuteTemplate(buf, name, nil)
            return buf.String(), err
        },
    }).Parse(src))

    if err := t.ExecuteTemplate(os.Stdout, "T2", nil); err != nil {
        panic(err)
    }
}

const src = `
{{define "T1"}}{{ printf "%s-%s" "complex" "stuff" }}{{end}}
{{define "T2"}}
    {{ $t1Out := (GetOutput "T1")}}
    {{ printf "%s-%s" "even-more" $t1Out }}
{{end}}`

Output will be (try it on the Go Playground):

    even-more-complex-stuff

The "T1" template simply outputs "complex-stuff", and the "T2" template gets the output of "T1", and concatenates the static text "even-more-" and the result of "T1".

The registered GetOutput function gets the name of a template to execute, executes it by directing its output to a local buffer, and returns the content of the buffer (along with the optional error of its execution).

Edit: I've found an exact duplicate: Capture or assign golang template output to variable

查看更多
登录 后发表回答