我想使用一个模板函数来扩展默认的Golang模板函数,该模板可以呈现另一个Golang模板,而该模板也应该有权访问有问题的函数。
以下演示案例应创建一个模板函数,该函数呈现也可以包含相同函数的给定模板。但是,该示例(正确地)引发了初始化周期错误。includeinclude
Golang 模板函数是否可以在引用自身时呈现另一个模板?
https://play.golang.org/p/hml-GDhV1HI
package main
import (
"bytes"
"errors"
html_template "html/template"
"os"
)
var includeFuncs = map[string]interface{}{
"include": func(templatePath string, data interface{}) (string, error) {
templatePath = "templates/" + templatePath
if _, err := os.Stat(templatePath); err != nil {
return "", errors.New("Unable to find the template file " + templatePath)
}
var renderedTpl bytes.Buffer
tpl, err := html_template.New(templatePath).Funcs(GetHTMLIncludeFuncs()).Parse(templatePath)
if err != nil {
return "", err
}
if err := tpl.Execute(&renderedTpl, data); err != nil {
return "", err
}
return renderedTpl.String(), nil
},
}
func GetHTMLIncludeFuncs() html_template.FuncMap {
return html_template.FuncMap(includeFuncs)
}
慕标琳琳
相关分类