Embed directive
//go:embed
Directives support compiling single-file, multi-file or directory embedding intoembed.FS类型变量
orstring/[]byte变量
- The embed.FS embedded file system provides three methods
- read the specified directory
func (f FS) ReadDir(name string) ([]fs.DirEntry, error)
- read the specified file
func (f FS) ReadFile(name string) ([]byte, error)
- Open the specified file
func (f FS) Open(name string) (fs.File, error)
- read the specified directory
Gin project as an example
* main.go
* go.mod
* static
* js
* css
* template
* fragment
* header.html
* footer.html
* content
* home
* index.html
filesystem embedded global variables
//go:embed static
var staticFS embed.FS //static目录嵌入staticFS变量
//go:embed template
var templateFS embed.FS //template目录嵌入templateFS变量
Using the Embed file system
func init() {
router = gin.Default()
//使用嵌入式文件系统启动静态文件服务
subStatic, _ := fs.Sub(staticFS, "static")
router.StaticFS("/static", http.FS(subStatic))
//使用嵌入式文件系统加载模板
router.HTMLRender = loadTemplates()
}
func main() {
router.GET("/home/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "home/index.html", gin.H{})
})
}
//自定义模板引擎实现多模板功能,模板内容从嵌入式文件系统提取
//依赖github.com/gin-contrib/multitemplate
func loadTemplates() multitemplate.Renderer {
r := multitemplate.NewRenderer()
var fragments string
fragmentFiles, _ := templateFS.ReadDir("template/fragment")
for _, fragmentFile := range fragmentFiles {
fragmentFilePath := path.Join("template/fragment", fragmentFile.Name())
fragment, _ := templateFS.ReadFile(fragmentFilePath)
fragments += string(fragment)
}
contentDirs, _ := templateFS.ReadDir("template/content")
for _, contentDir := range contentDirs {
contentDirPath := path.Join("template/content", contentDir.Name())
contentFiles, _ := templateFS.ReadDir(contentDirPath)
for _, contentFile := range contentFiles {
contentFilePath := path.Join(contentDirPath, contentFile.Name())
tplName := strings.TrimPrefix(contentFilePath, "template/content/")
content, _ := templateFS.ReadFile(contentFilePath)
r.AddFromString(tplName, fragments+string(content))
}
}
return r
}
{{o.name}}
{{m.name}}