如何解决模板:模式与文件不匹配的问题

Abu*_*yem 3 file go embedded-resource go-templates

当我从除 main 之外的其他 go 文件访问文件时,如何处理文件路径。

\n

在 other.go 文件中,我尝试运行 ParseFS,但它给出了 template:pattern matches no files:templates/test.tmpl错误。这是我的文件树。

\n
\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 go.mod\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main\n\xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.go\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 other\n    \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 other.go\n    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 templates\n        \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 test.tmpl\n
Run Code Online (Sandbox Code Playgroud)\n

其他/其他.go

\n
package other\n\nimport (\n    "embed"\n    "fmt"\n    "html/template"\n)\n\nvar templateFS embed.FS\n\nfunc Check() error {\n    _, err := template.New("email").ParseFS(templateFS, "templates/"+ "test.tmpl")\n\n    if err != nil {\n        fmt.Println(err)\n    }\n    return nil\n}\n
Run Code Online (Sandbox Code Playgroud)\n

主/main.go

\n
func main() {\n    err :=othher.Check()\n\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

icz*_*cza 8

Go 是一种静态链接语言。无论您编写什么源代码,最终该go工具都会将其编译成可执行的二进制文件。之后运行二进制文件将不再需要源文件。

embed包为您提供了一种在可执行二进制文件中包含静态文件的方法,您可以在运行时访问这些静态文件(运行应用程序时不需要存在原始的包含文件)。

但是,该go工具不会神奇地找出您想要在二进制文件中包含哪些文件和文件夹。显然,它不会包含源或模块文件夹中的所有内容。

告知要包含哪些文件的方法是//go:embed在要存储文件的变量之前添加特殊注释。

因此,在您的情况下,您必须在templateFS变量之前添加以下注释:

//go:embed templates/*
var templateFS embed.FS
Run Code Online (Sandbox Code Playgroud)

另请注意,嵌入仅在导入embed包时才有效。这种情况“自然”发生在您的情况下,因为您使用了embed.FS类型(需要导入embed包),但是如果您将文件包含在string[]byte类型的变量中,则不需要 importing embed,在这种情况下您必须进行“空白”导入,例如

import _ "embed"
Run Code Online (Sandbox Code Playgroud)

更多详细信息请参阅 的包文档embed

请参阅相关问题:在 Go 程序中捆绑静态资源的最佳方式是什么?