捕获或分配 golang 模板输出给变量 [英] Capture or assign golang template output to variable
问题描述
在模板中,我怎样才能做到这一点?
Within a template, how can I achieve this?
{{$var := template "my-template"}}
我只是得到操作数中意外的<模板>"
.
推荐答案
没有用于获取模板执行结果的内置"操作,但您可以通过注册一个执行该操作的函数来实现.
There is no "builtin" action for getting the result of a template execution, but you may do it by registering a function which does that.
您可以使用 Template.Funcs()
函数,您可以使用 Template.ExecuteTemplate 执行命名模板()
并且您可以使用 bytes.Buffer
作为目标(将模板执行结果直接放入缓冲区).
You can register functions with the Template.Funcs()
function, you may execute a named template with Template.ExecuteTemplate()
and you may use a bytes.Buffer
as the target (direct template execution result into a buffer).
这是一个完整的例子:
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 {
panic(err)
}
}
const tmpl = `{{define "my-template"}}my-template content{{end}}
See result:
{{$var := execTempl "my-template"}}
{{$var}}
`
输出(在 Go Playground 上试试):
Output (try it on the Go Playground):
See result:
my-template content
"my-template"
模板由注册的函数execTempl()
执行,结果作为string
返回,它存储在 $var
模板变量中,然后它会被简单地添加到输出中,但如果需要,您可以使用它传递给其他函数.
The "my-template"
template is executed by the registered function execTempl()
, and the result is returned as a string
, which is stored in the $var
template variable, which then is simply added to the output, but you may use it to pass to other functions if you want to.
这篇关于捕获或分配 golang 模板输出给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!