捕获或分配golang模板输出到变量 [英] Capture or assign golang template output to variable
问题描述
在一个模板中,我该如何做到这一点?
{{$ var:= templatemy-template} }
我只是在操作数中出现意外< template> code>。
获取模板执行结果没有内建操作,但可以通过注册一个可以实现这一点的函数来实现它。
您可以使用 Template.Funcs()
函数,您可以使用 Template.ExecuteTemplate()
,您可以使用<一个href =https://golang.org/pkg/bytes/#Buffer =nofollow> bytes.Buffer
作为目标(直接
以下是一个完整的示例:
var t * te mplate.Template
func execTempl(name string)(string,error){
buf:=&; bytes.Buffer {}
err:= t.ExecuteTemplate(buf,名称,无)
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 =`{{definemy-template}} my-template content { {end}}
查看结果:
{{$ var:= execTemplmy-template}}
{{$ var}}
`
输出(在 Go Playground ):
查看结果:
my-template内容
my-template
模板由注册函数 execTempl()
执行,结果作为字符串
返回,存储在 $ var
模板变量,然后将其简单地添加到输出中,但您可以使用它来传递给其他函数。
Within a template, how can I achieve this?
{{$var := template "my-template"}}
I just get "unexpected <template> in operand"
.
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.
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).
Here is a complete example:
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}}
`
Output (try it on the Go Playground):
See result:
my-template content
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屋!