Home >Backend Development >Golang >How to Capture Go Template Output into a Variable?

How to Capture Go Template Output into a Variable?

Susan Sarandon
Susan SarandonOriginal
2024-12-23 04:47:15714browse

How to Capture Go Template Output into a Variable?

Capturing Template Output in Go

Within a Go template, it's impossible to directly assign a template output to a variable using the syntax {$var := template}. Instead, it's necessary to register a custom function to capture the template output.

Function Registration

To register a function, use the Template.Funcs() function. It allows you to define a set of functions that can be used within your template.

Template Execution

To execute a named template and capture its output, use Template.ExecuteTemplate(). This function takes a buffer as its target, allowing you to directly write the template output into the buffer.

Example

Here's an example that demonstrates the use of a registered function to capture template output:

package main

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

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:

See result:

my-template content

In this example, the execTempl() function is registered and used within the template to execute the "my-template" template and capture its output, which is then assigned to the $var template variable and displayed in the output.

The above is the detailed content of How to Capture Go Template Output into a Variable?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn