Call other templates with dynamic name

Viewed 6878

I do not see a way to call templates (text or html) with a dynamic name. Example:

This works:

{{template "Blah" .}}

This errors with "unexpected "$BlahVar" in template invocation":

{{$BlahVar := "Blah"}}
{{template $BlahVar .}}

The overall problem I'm trying to solve is that I need to render templates conditionally based on a configuration file - so I don't know the names of the templates ahead of time. Obviously I can put a function in the FuncMap which just does a separate template parsing and invocation and returns that result but was wondering if there is a Better Way.

5 Answers

Using htmltemplate.HTML() to inject parsed template("email/test") on another template("email/main")

htmlTplEngine := htmltemplate.New("htmlTplEngine")


_, htmlTplEngineErr := htmlTplEngine.ParseGlob("views/email/*.html")
if nil != htmlTplEngineErr {
    log.Panic(htmlTplEngineErr.Error())
}

var contentBuffer bytes.Buffer
if err := htmlTplEngine.ExecuteTemplate(&contentBuffer, "email/test", params); err != nil {
    return "", "", errors.Wrap(err, "execute content html")
}

var templateBuf bytes.Buffer
if err := htmlTplEngine.ExecuteTemplate(
    &templateBuf,
    "email/main",
    map[string]interface{}{
        "Content": htmltemplate.HTML(contentBuffer.String()),
        "Lang":    language,
    },
); err != nil {
    return "", "", errors.Wrap(err, "execute html template")
}

On "email/main"

{{define "email/main"}}

My email/test template: {{.Content}}

{{end}}

Faced the same issue while using gin, and simplest solution was:

router.GET("/myurl", func(ctx *gin.Context) {
    /*
       --- do anything here --
    */
    template1 := "template1.html"
    template2 := "template2.html"

    ctx.HTML(200, template1, nil)
    ctx.HTML(200, template1, nil)
})

Basically I split the html content into separated files, and call them up individually. As long as the response code is the same (for example: 200), then it won't be triggering any issue.

Related