我的 golang 代码拱门如下:├── embeded.go├── go.mod├── json│ └── file└── main.go这是我的 embede.go 代码:package mainimport "embed"//go:embed json/*var templatesFS embed.FSfunc TemplatesFS() embed.FS { return templatesFS}现在在我的 main.go 中我无法访问 json 目录中的文件:package mainimport ( "fmt" "log" "os" "text/template")func main() { tmpl := template.Must( template.New("json/file"). ParseFS(TemplatesFS(), "json/file")) if err := tmpl.Execute(os.Stdout, "config"); err != nil { log.Fatal(err) }}当我运行上面的代码时出现错误template: json/file: "json/file" is an incomplete or empty templatefile但我可以这样访问:file, err := TemplatesFS().ReadFile("json/file")那为什么我不能在 templte.execute 中访问它呢?我该如何解决?
1 回答

子衿沉夜
TA贡献1828条经验 获得超3个赞
模板解析器成功地从嵌入式文件系统中读取了一个模板。
Execute 方法报告模板tmpl不完整。该变量tmpl设置为调用 New 创建的模板。模板不完整,因为应用程序未使用模板名称解析模板json/file。
ParseFS 使用文件的基本名称命名模板。通过在对 New 的调用中使用文件的基本名称来修复。
tmpl := template.Must(
template.New("file").ParseFS(TemplatesFS(), "json/file"))
- 1 回答
- 0 关注
- 113 浏览
添加回答
举报
0/150
提交
取消