ajaxgohtml-templates

How can I "compile" an HTML template but not "execute" it?


I'm using Go HTML templates and when you run this function it sends the data to the client, but I would like to store that data in a variable and send it to the client later. How can this be achieved?

func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error

This is for use in an AJAX response. I know on the client side I could simply parse the xhr.responseText, but I need to send some other variables with it.


Solution

  • Use a buffer:

    buf:=bytes.Buffer{}
    t.ExecuteTemplate(&buf,"name",data)
    

    Then you can use buf.Bytes(), or buf.String().