我已经使用以下代码将模板文件加载到内存中:
t := template.New("master")
tpl, err := t.ParseFiles("templates/index.html")
现在我想将该模板绘制成一个字符串,所以我index.html
的很空:
{{define "master"}}
Hello World
{{end}}
我刚刚开始,所以我还没有任何数据。有没有办法可以将Template
对象转换为没有数据的字符串?
我已经使用以下代码将模板文件加载到内存中:
t := template.New("master")
tpl, err := t.ParseFiles("templates/index.html")
现在我想将该模板绘制成一个字符串,所以我index.html
的很空:
{{define "master"}}
Hello World
{{end}}
我刚刚开始,所以我还没有任何数据。有没有办法可以将Template
对象转换为没有数据的字符串?
如果您的模板(尚未)使用任何变量,您可以将任何值作为数据传递以呈现模板。因此,要将模板呈现到标准输出,您可以例如使用:
tpl.Execute(os.Stdout, nil)
如果你真的想把模板渲染成字符串,可以使用 abytes.Buffer
作为中介:
var buf bytes.Buffer
tpl.Execute(&buf, nil)
str := buf.String()
按照设计,这在 Go 中是不可能的 - 如果您没有数据,则 Template 包是不必要的开销。
如果您没有数据,只需使用io
包读取文件,而不是使用模板。