I’m having some issues loading templates using Gin. Specifically, after setting up my templates, when I try to run my app with go run main.go I am getting the below error.
How do I load the templates correctly?
➜ app git:(main) ✗ go run main.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
panic: open templates/*: no such file or directory
I am loading the templates like so.
func main() {
router := setupRouter()
router.Run()
}
func setupRouter() *gin.Engine {
router := gin.Default()
templ := template.Must(template.New("").ParseFiles("templates/*"))
router.SetHTMLTemplate(templ)
router.StaticFS("/static", http.Dir("static"))
router.SetTrustedProxies([]string{"127.0.0.1"})
routes.InitializeRoutes(&router.RouterGroup)
return router
}
And calling them on my route.
func GetIndex(c *gin.Context) {
c.HTML(http.StatusOK, "home.tmpl.html", gin.H{
"title": "Home Page",
})
}
This is my folder structure
├── controllers
├── go.mod
├── go.sum
├── main.go
├── models
├── public
├── routes
│ ├── general
│ │ └── general.go
│ └── routes.go
└── templates
├── base.tmpl.html
├── footer.tmpl.html
└── home.tmpl.html
>Solution :
In your setupRouter function, you are using template.ParseFiles to parse the template files. The argument to ParseFiles should be a list of file names, not a file pattern. So, instead of "templates/*", you should use a slice of file names like this:
templ := template.Must(template.ParseFiles(
"templates/base.tmpl.html",
"templates/footer.tmpl.html",
"templates/home.tmpl.html",
))
This will parse the three template files in the templates directory and create a single template that includes all of them.
Alternatively, you can use filepath.Glob to get a list of file names that match a pattern:
files, err := filepath.Glob("templates/*.tmpl.html")
if err != nil {
log.Fatal(err)
}
templ := template.Must(template.ParseFiles(files...))
This will get a list of all .tmpl.html files in the templates directory and parse them into a single template.
Either of these approaches should solve the issue and allow your application to find and load the template files correctly.