I'm pretty inexperienced with go templates and I've got a situation where I have a top level template, into which I want to dynamically inject inner templates, in which there should be some injected value. The solution I have works, it looks ugly or naive to me. The code below is contrived, but represents accurately what I've come up with.
First, the inner template is executed, setting the "Value" to produce a String, which is then injected into the wrapping template "top".
Is there a way to combine these steps into a single invocation, such that the inner template is evaluated with the value, and the injected into the outer template?
package main
import (
"bytes"
"fmt"
"text/template"
)
// top should dynamically wrap an inner template.
const top = `Top, inner: {{.Inner}}
`
const inner1 = `Inner1: {{.Value}}
`
const inner2 = `Inner2: {{.Value}}
`
var innerds = []string{"inner1", "inner2"}
var t = new(template.Template)
// hardcoded for simplicity, dynamic IRL
var val = struct {
Value string
}{"foobar!"}
func main() {
template.Must(t.New("top").Parse(top))
template.Must(t.New("inner1").Parse(inner1))
template.Must(t.New("inner2").Parse(inner2))
for _, innerTmpName := range innerds {
innerBuf := new(bytes.Buffer)
_ = t.ExecuteTemplate(innerBuf, innerTmpName, val) // innerBuf == "Inner1: foobar!"
fmt.Println(innerBuf.String())
topBuf := new(bytes.Buffer)
_ = t.ExecuteTemplate(topBuf, "top", struct{Inner string}{innerBuf.String()}) // topBuf == "Top, inner: Inner1: foobar!"
fmt.Println(topBuf.String())
}
}
Output:
Top, inner: Inner1: foobar!
Top, inner: Inner2: foobar!