从另一个模板中获取go模板的值 [英] get the value of a go template from inside another template

查看:59
本文介绍了从另一个模板中获取go模板的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模板T1和T2.我想获取T1的输出,并在T2内对其进行一些额外的处理.我的问题是:

如何将T1的输出存储在T2内的变量中?这有可能吗?

这是一些伪模板:

  {{定义"T1"}}{{printf%s-%s"复杂的内容}}{{结尾}}{{定义"T2"}}{{$ some_var:= output_from_template"T1"}}{{ 等等 }}{{结尾}} 

解决方案

没有内置支持将模板结果存储在模板变量中,仅用于包含结果.

但是您可以使用任何所需的复杂功能注册自定义功能.您可以注册一个 GetOutput 函数,该函数将执行由其名称标识的模板,并且该函数可以将结果作为 string 返回,可以将其存储在模板变量中./p>

执行此操作的示例:

  func main(){t:= template.New(")t = template.Must(t.Funcs(template.FuncMap {"GetOutput":func(名称字符串)(字符串,错误){buf:=& bytes.Buffer {}err:= t.ExecuteTemplate(buf,name,nil)返回buf.String(),错误},}).Parse(src))如果err:= t.ExecuteTemplate(os.Stdout,"T2",nil);err!= nil {恐慌}}const src =`{{define"T1"}} {{printf%s-%s""complex""stuff"}} {{end}}{{定义"T2"}}{{$ t1Out:=(GetOutput"T1")}}{{printf%s-%s"甚至更多" $ t1Out}}{{end}}` 

输出将是(在进入游乐场上尝试):

 甚至更复杂的东西 

"T1" 模板仅输出"complex-stuff" ,而"T2" 模板获取"T1" ,并连接静态文本"even-more-" "T1" 的结果.

已注册的 GetOutput 函数获取要执行的模板的名称,通过将其输出定向到本地缓冲区来执行该模板,然后返回该缓冲区的内容(以及其执行的可选错误)).

我发现了一个完全相同的副本:

There is no builtin support for storing the result of a template in a template variable, only for the inclusion of the result.

But you can register custom functions with any complex functionality you want. You may register a GetOutput function which would execute a template identified by its name, and it could return the result as a string, which you can store in a template variable.

Example doing this:

func main() {
    t := template.New("")

    t = template.Must(t.Funcs(template.FuncMap{
        "GetOutput": func(name string) (string, error) {
            buf := &bytes.Buffer{}
            err := t.ExecuteTemplate(buf, name, nil)
            return buf.String(), err
        },
    }).Parse(src))

    if err := t.ExecuteTemplate(os.Stdout, "T2", nil); err != nil {
        panic(err)
    }
}

const src = `
{{define "T1"}}{{ printf "%s-%s" "complex" "stuff" }}{{end}}
{{define "T2"}}
    {{ $t1Out := (GetOutput "T1")}}
    {{ printf "%s-%s" "even-more" $t1Out }}
{{end}}`

Output will be (try it on the Go Playground):

    even-more-complex-stuff

The "T1" template simply outputs "complex-stuff", and the "T2" template gets the output of "T1", and concatenates the static text "even-more-" and the result of "T1".

The registered GetOutput function gets the name of a template to execute, executes it by directing its output to a local buffer, and returns the content of the buffer (along with the optional error of its execution).

Edit: I've found an exact duplicate: Capture or assign golang template output to variable

这篇关于从另一个模板中获取go模板的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆