Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang template can't access file in embedFS

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

The error reports that the template named in the argument to New is incomplete. The template in the file json/file is named file. Use that name when parsing the template:

tmpl := template.Must(
    template.New("file").ParseFS(TemplatesFS(), "json/file"))     
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading