如何“编译”一个HTML模板但不“执行”它?

huangapple go评论71阅读模式
英文:

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

问题

我正在使用Go的HTML模板,当你运行这个函数时,它会将数据发送给客户端,但我想将这些数据存储在一个变量中,并稍后将其发送给客户端。如何实现这个目标?

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

这是用于AJAX响应的。我知道在客户端上,我可以简单地解析xhr.responseText,但我需要将一些其他变量与其一起发送。

英文:

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.

答案1

得分: 2

使用缓冲区:

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

然后你可以使用 buf.Bytes()buf.String()

英文:

Use a buffer:

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

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

huangapple
  • 本文由 发表于 2022年9月9日 09:55:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/73656583.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定