dsfadsa08911 2018-01-15 11:55
浏览 4
已采纳

从另一个模板中获取go模板的值[重复]

This question already has an answer here:

I have two templates T1 and T2. I want to get the output of T1 and do a some extra processing on it inside T2. My question is:

how do I store the output of T1 in a variable inside T2? Is this even possible?

Here's some pseudo-template:

{{define "T1"}}
    {{ printf "%s-%s" complex stuff }}
{{end}}
{{define "T2"}}
    {{ $some_var := output_from_template "T1"}}  <<<<<<<<<<<
    {{ etc }}
{{end}}
</div>
  • 写回答

1条回答 默认 最新

  • dphnn333971 2018-01-15 12:41
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答