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

How to solve template: pattern matches no files

How to handle file path when i am accessing file from other go file than main.

in other.go file i am trying to run ParseFS but it’s giving the template: pattern matches no files: templates/test.tmpl error. Here is my file tree.

├── go.mod
├── main
│   └── main.go
└── other
    ├── other.go
    └── templates
        └── test.tmpl

other/other.go

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 other

import (
    "embed"
    "fmt"
    "html/template"
)

var templateFS embed.FS

func Check() error {
    _, err := template.New("email").ParseFS(templateFS, "templates/"+ "test.tmpl")

    if err != nil {
        fmt.Println(err)
    }
    return nil
}

main/main.go

func main() {
    err :=othher.Check()

    if err != nil {
        fmt.Println(err)
    }
}

>Solution :

Go is a statically linked language. Whatever source you write, in the end the go tool will compile it into an executable binary. The source files will not be required afterwards to run the binary.

The embed package gives you a mean to include static files in the executable binary which you can access at runtime (the original, included files don’t need to be present when you run the app).

However, the go tool will not magically find out what files and folders you want to include in your binary. It will obviously not include everything you have in your source or module’s folder.

The way to tell which files you want to be included is a special //go:embed comment preceding the variable you want the files to be stored in.

So in your case you have to put the following comment before your templateFS variable:

//go:embed templates/*
var templateFS embed.FS

Also note that embedding only works if you import the embed package. This "naturally" happens in your case because you used the embed.FS type (which requires importing the embed package), but if you would include a file in a variable of string or []byte type, that wouldn’t require importing embed, in which case you’d have to do a "blank" import like

import _ "embed"

More details are in the package doc of embed.

See related question: What's the best way to bundle static resources in a Go program?

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