Within a Go template, the goal is to emulate the following:
{{$var := template "my-template"}}
However, this approach results in the error "unexpected in operand."
Go does not provide an inbuilt method to capture template execution results. Instead, register a function that performs this task.
Use the Template.Funcs() function to register functions. Execute named templates with Template.ExecuteTemplate() and use a bytes.Buffer as the target to capture the direct template execution result into a buffer.
package main import ( "bytes" "html/template" "log" "os" ) 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 { log.Fatal(err) } } const tmpl = `{{define "my-template"}}my-template content{{end}} See result: {{$var := execTempl "my-template"}} {{$var}} `
Execute the "my-template" template using the registered execTempl() function. Store the result in the $var template variable, which can then be added to the output or passed to other functions.
See result: my-template content
Note that the output captures the result of the "my-template" template and displays it within the main template.
The above is the detailed content of How to Capture Go Template Output and Assign it to a Variable?. For more information, please follow other related articles on the PHP Chinese website!