Home > Software design >  Golang template can't access file in embedFS
Golang template can't access file in embedFS

Time:09-16

my golang code arch is as bellow:

├── embeded.go
├── go.mod
├── json
│   └── file
└── main.go

and this is my embede.go code:

package main

import "embed"

//go:embed json/*
var templatesFS embed.FS

func TemplatesFS() embed.FS {
    return templatesFS
}

now in my main.go I can't access file in json directory:

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)
    }
}

when I run above code I got error template: json/file: "json/file" is an incomplete or empty template

but I can access the file like this:

file, err := TemplatesFS().ReadFile("json/file")

so why I can't access it in templte.execute ?

How Can I Solve It ?

CodePudding user response:

The template parser successfully read a template from the embedded file system.

The Execute method reports that the template tmpl is incomplete. The variable tmpl is set to the template created by the call to New. The template is incomplete because the application did not parse a template with the template's name, json/file.

ParseFS names templates using the file's base name. Fix by using using the file's base name in the call to New.

tmpl := template.Must(
    template.New("file").ParseFS(TemplatesFS(), "json/file"))     
  • Related