Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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 ?

like image 853
Mohammad Abdollahzadeh Avatar asked Sep 03 '25 17:09

Mohammad Abdollahzadeh


1 Answers

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!