get the value of a go template from inside another template [duplicate]

痞子三分冷 提交于 2019-12-24 19:16:48

问题


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:


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



来源:https://stackoverflow.com/questions/48262519/get-the-value-of-a-go-template-from-inside-another-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!