golang template模板 template: xxx.html is an incomplete or empty template 解决方法

当我们在使用go语言中的template渲染多个模板文件时,如果我们使用的模板文件没有使用  ParseFiles方法进行解析就直接在模板里面使用 template进行嵌套的话就会出现 template: xxx.html is an incomplete or empty template 的异常。

解决方法: 在我们使用的时候先将可能用到的模板文件全部扫描后用ParseFiles进行解析以下即可。

tplFile = "index.html"
wr := bytes.NewBufferString("")
data:= make(map[string]interface{})


// 先获取所有待使用的模板文件列表
var tplFiles []string
filepath.WalkDir("templates", func(path string, d fs.DirEntry, err error) error {
	if !d.IsDir() && strings.HasSuffix(d.Name(), ".html") {
		// 非目录,且是.html结尾的文件加入到模板文件列表
		tplFiles = append(tplFiles, path)
	}
	return nil
})


t := template.New("") // 获取Template对象,注意这里名称 可为空,也可以指定名称

tpl, err := t.ParseFiles(tplFiles...) // 解析所有的模板文件

tpl.ExecuteTemplate(wr, tplFile, data) // 渲染指定的模板文件

//tpl.Execute(buf,data) // 渲染template.New("xxx.html")这里指定的模板文件

核心问题就是将所有可能用到的模板在模板渲染之前都解析以下。  tpl, err := t.ParseFiles(tplFiles...) // 解析所有的模板文件 

ParseFiles方法原型定义和说明

func (t *template.Template) ParseFiles(filenames ...string) (*template.Template, error)

ParseFiles parses the named files and associates the resulting templates with t. If an error occurs, parsing stops and the returned template is nil; otherwise it is t. There must be at least one file.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

ParseFiles returns an error if t or any associated template has already been executed.

ParseFiles解析命名文件,并将生成的模板与t相关联。如果发生错误,解析将停止,返回的模板为nil;否则为t。必须至少有一个文件。

当解析不同目录中具有相同名称的多个文件时,最后提到的将是结果。

如果t或任何相关模板已经执行,ParseFiles将返回一个错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tekin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值