首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >template.Execute()与template.ExecuteTemplate()

template.Execute()与template.ExecuteTemplate()
EN

Stack Overflow用户
提问于 2021-12-28 11:25:58
回答 1查看 468关注 0票数 -1

以下代码生成错误:

代码语言:javascript
复制
panic: template: body: "body" is an incomplete or empty template
代码语言:javascript
复制
//go:embed resources/*
var res embed.FS

func main() {
    root, _ := fs.Sub(res, "resources")
    t, err := template.New("body").ParseFS(root, "home.html")
    assert(err)
    assert(t.Execute(os.Stdout, nil))
}

模板文件resources/home.html非常简单:

代码语言:javascript
复制
{{define "body"}}
Hello World!
{{end}}

如果我将main()的最后一行更改为t.ExecuteTemplate(os.Stdout, "body", nil),那么问题就解决了。

从库源代码中,我注意到错误是因为:

代码语言:javascript
复制
func (t *Template) execute(wr io.Writer, data interface{}) (err error) {
    ... ...
    if t.Tree == nil || t.Root == nil {
        state.errorf("%q is an incomplete or empty template", t.Name())
    }
    ... ...
}

但是为什么 t.Treet.Rootnil?我的围棋版本是:

代码语言:javascript
复制
go version go1.17.5 linux/amd64
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-29 02:31:03

我发现了问题。VSCode自动为我导入text/template。此包不能正确解析{{define "..."}}指令。

使用html/template工作正常。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70506364

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档