Home >Backend Development >Golang >How to Assign Golang Template Output to a Variable?
In Go, you can define and execute templates that can dynamically generate HTML or other text formats. One may want to capture the output of a template and assign it to a variable.
This is not directly possible using Go's built-in templating language. Attempting to do so, as in the following example, will result in a "unexpected in operand" error:
{{$var := template "my-template"}}
To bypass this limitation, you can register a custom function that retrieves the template output. Here's how to do it:
var t *template.Template // execTempl retrieves the output of a named template. func execTempl(name string) (string, error) { buf := &bytes.Buffer{} // Create a buffer to store the template output. err := t.ExecuteTemplate(buf, name, nil) // Execute the template into the buffer. return buf.String(), err }
t = template.Must(template.New("").Funcs(template.FuncMap{ "execTempl": execTempl, }).Parse(tmpl))
if err := t.Execute(os.Stdout, nil); err != nil { panic(err) }
In your template, you can use the registered "execTempl" function to retrieve the output of a named template and assign it to a variable:
const tmpl = `{{define "my-template"}}my-template content{{end}} See result: {{$var := execTempl "my-template"}} {{$var}} `
Here is a complete example that demonstrates the usage of this technique:
package main import ( "bytes" "fmt" "os" "text/template" ) const tmpl = `{{define "my-template"}}my-template content{{end}} See result: {{$var := execTempl "my-template"}} {{$var}} ` func main() { execTempl := func(name string) (string, error) { buf := &bytes.Buffer{} err := t.ExecuteTemplate(buf, name, nil) return buf.String(), err } t := template.Must(template.New("").Funcs(template.FuncMap{ "execTempl": execTempl, }).Parse(tmpl)) if err := t.Execute(os.Stdout, nil); err != nil { fmt.Println(err) } }
Running the above program will produce the following output:
See result: my-template content
By using this technique, you can capture the output of arbitrary templates and store it in variables for further processing or presentation.
The above is the detailed content of How to Assign Golang Template Output to a Variable?. For more information, please follow other related articles on the PHP Chinese website!