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

How to Capture Go Template Output into a Variable?

Susan Sarandon
Release: 2024-12-23 04:47:15
Original
720 people have browsed it

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}}
`
Copy after login

Output:

See result:

my-template content
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template