bitsofinfo
bitsofinfo

Reputation: 1054

Capture or assign golang template output to variable

Within a template, how can I achieve this?

{{$var := template "my-template"}}

I just get "unexpected <template> in operand".

Upvotes: 15

Views: 16976

Answers (2)

IanB
IanB

Reputation: 2694

A more straightforward approach than @icza's answer:

package main

import (
    "bytes"
    "fmt"
    "html/template"
)

func main() {
    input := "/accounts/{{ .accountID }}"

    var output bytes.Buffer

    templ := template.Must(template.New("getAccount").Parse(input))
    templ.Execute(&output, map[string]interface{}{
        "accountID": 100,
    })

    fmt.Println(output.String())
}

This will print /accounts/100

Go playground: https://play.golang.com/p/u5PdxOfDKi7

Upvotes: 1

icza
icza

Reputation: 417622

There is no "builtin" action for getting the result of a template execution, but you may do it by registering a function which does that.

You can register functions with the Template.Funcs() function, you may execute a named template with Template.ExecuteTemplate() and you may use a bytes.Buffer as the target (direct template execution result into a buffer).

Here is a complete example:

var t *template.Template

func execTempl(name string) (string, error) {
    buf := &bytes.Buffer{}
    err := t.ExecuteTemplate(buf, name, nil)
    return buf.String(), err
}

func main() {
    t = template.Must(template.New("").Funcs(template.FuncMap{
        "execTempl": execTempl,
    }).Parse(tmpl))
    if err := t.Execute(os.Stdout, nil); err != nil {
        panic(err)
    }
}

const tmpl = `{{define "my-template"}}my-template content{{end}}
See result:
{{$var := execTempl "my-template"}}
{{$var}}
`

Output (try it on the Go Playground):

See result:

my-template content

The "my-template" template is executed by the registered function execTempl(), and the result is returned as a string, which is stored in the $var template variable, which then is simply added to the output, but you may use it to pass to other functions if you want to.

Upvotes: 20

Related Questions