模板和自定义函数;错误:在 <"funcName"> 处执行 "templName" 不是定义函数

Template and custom function; err: executing "templName" at <"funcName"> is not a define function

我用 template.AddParseTree 方法添加了一些文本以附加模板文本,但是有一个奇怪的行为,该方法应该像这样使用它:

singleTemplate=anyTemplate
targetTemplate=*template.Must(targetTemplate.AddParseTree(e.Name, anyTemplate.Tree))

但是当 singleTemplate 有一个功能时它不工作,出于一个奇怪的原因它只在我这样做时才工作

singleTemplate=anyTemplate
targetTemplate=*template.Must(singleTemplate.AddParseTree(e.Name, anyTemplate.Tree))

但它不能那样工作,因为我将无法附加任何其他内容 您可以在这里尝试:https://play.golang.org/p/f5oXNzD1fKP

package main

import (
    "log"
    "os"
    "text/template"
)

var funcionIncremento = template.FuncMap{
    "inc": func(i int) int {
        return i + 1
    },
}

func main() {

    var strs []string
    strs = append(strs, "test1")
    strs = append(strs, "test2")
    //-----------------Not valid(it would)
    var probar1 = template.Template{}
    var auxiliar1 = template.Template{}
    auxiliar1 = *template.Must(template.New("test").Funcs(funcionIncremento).Parse(`
            {{range $index, $element := .}}
                Number: {{inc $index}}
            {{end}}
    `))

    probar1 = *template.Must(probar1.AddParseTree("test", auxiliar1.Tree))
    err := probar1.ExecuteTemplate(os.Stdout, "test", &strs)
    if err != nil {
        log.Println("Error1: ", err)
    }
//--------------------------------valid(it wouldn´t), because I wouldn´t be able to append
    var probar2 = template.Template{}
    var auxiliar2 = template.Template{}
    auxiliar2 = *template.Must(template.New("test").Funcs(funcionIncremento).Parse(`
            {{range $index, $element := .}}
                Number: {{inc $index}}
            {{end}}
    `))

    probar2 = *template.Must(auxiliar2.AddParseTree("test", auxiliar2.Tree))
    err = probar2.ExecuteTemplate(os.Stdout, "test", &strs)
    if err != nil {
        log.Println("Error2: ", err)
    }
    //-------------------------------------------
}

a.AddParseTree("t", b.Tree) 仅添加 模板 bparse.Tree 它不添加 b 的功能,因为它们是不是 parse.Tree 类型的一部分,它们是 template.Template 类型的一部分。

任何 b 需要使用的功能,也必须添加到 a

var probar1 = template.New("pro").Funcs(funcionIncremento)
var auxiliar1 = template.New("aux").Funcs(funcionIncremento)

auxiliar1 = template.Must(auxiliar1.Parse(`
        {{range $index, $element := .}}
            Number: {{inc $index}}
        {{end}}
`))

probar1 = template.Must(probar1.AddParseTree("test", auxiliar1.Tree))
err := probar1.ExecuteTemplate(os.Stdout, "test", &strs)
if err != nil {
    log.Println("Error1: ", err)
}