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}}
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 astring
, which you can store in a template variable.Example doing this:
Output will be (try it on the Go Playground):
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