Golang 模板无法访问 embedFS 中的文件

我的 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 中访问它呢?


我该如何解决?


皈依舞
浏览 114回答 1
1回答

子衿沉夜

模板解析器成功地从嵌入式文件系统中读取了一个模板。Execute 方法报告模板tmpl不完整。该变量tmpl设置为调用 New 创建的模板。模板不完整,因为应用程序未使用模板名称解析模板json/file。ParseFS 使用文件的基本名称命名模板。通过在对 New 的调用中使用文件的基本名称来修复。tmpl := template.Must(    template.New("file").ParseFS(TemplatesFS(), "json/file")) 
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go