我的 golang 代碼拱如下:
├── embeded.go
├── go.mod
├── json
│ └── file
└── main.go
這是我的 embede.go 代碼:
package main
import "embed"
//go:embed json/*
var templatesFS embed.FS
func TemplatesFS() embed.FS {
return templatesFS
}
現在在我的 main.go 中,我無法訪問 json 目錄中的檔案:
package main
import (
"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 template
但我可以訪問file
這樣的:
file, err := TemplatesFS().ReadFile("json/file")
那么為什么我不能在 templte.execute 中訪問它呢?
我該如何解決?
uj5u.com熱心網友回復:
錯誤報告在 New 的引數中命名的模板不完整。檔案中的模板json/file
名為file
. 決議模板時使用該名稱:
tmpl := template.Must(
template.New("file").ParseFS(TemplatesFS(), "json/file"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/508320.html