我的 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 關注
- 106 瀏覽
添加回答
舉報
0/150
提交
取消