当我从非主要的go文件访问文件时,如何处理文件路径。
在other.go文件中,我尝试运行ParseFS,但它会出现错误信息:模板:模式不匹配任何文件:templates/test.tmpl
。这是我的文件树结构。
├── go.mod
├── main
│ └── main.go
└── other
├── other.go
└── templates
└── test.tmpl
other/other.go
package other
import (
"embed"
"fmt"
"html/template"
)
var templateFS embed.FS
func Check() error {
_, err := template.New("email").ParseFS(templateFS, "templates/"+ "test.tmpl")
if err != nil {
fmt.Println(err)
}
return nil
}
main/main.go
func main() {
err :=othher.Check()
if err != nil {
fmt.Println(err)
}
}
templateFS
前面有一个不正确的//go:embed
指令,这是您在答案中小心省略的。请展示一下。 - icza