I'm using Golang 1.21.1 on Ubuntu 20.04 and Fiber 2.50. I'm having problems rendering other templates than index
.
Here is the snippet that defines how templates will be rendered, the middleware list and the router:
config := fiber.Config{
Views: html.NewFileSystem(http.Dir("./templates"), ".html"),
ViewsLayout: "main",
}
// Create a new Fiber server.
server := fiber.New(config)
// Add Fiber middlewares.
server.Use(logger.New())
server.Static("/static", "./static")
// Router
server.Get("/:page", pageViewHandler)
server.Get("/", indexViewHandler)
// return server.Listen(fmt.Sprintf(":%d", port))
return server.Listen(":5000")
The templates
directory has the following structure
templates/
├── main.html
└── pages
├── about.html
└── index.html
index.html
and about.html
simply show their names to see which file had been used.
Finally, he is how the handlers are defined:
// indexViewHandler handles a view for the index page.
func indexViewHandler(c *fiber.Ctx) error {
log.Printf("in indexViewHandler()")
return c.Render("pages/index", nil)
}
// pageViewHandler handles a view for any other page.
func pageViewHandler(c *fiber.Ctx) error {
log.Printf("in pageViewHandler()")
filename := c.Params("page")
path := fmt.Sprintf("pages/%s", filename)
log.Printf("path=%s\n", path)
return c.Render(path, nil)
}
When I invoke localhost:5000/
I get the index page with the following log:
2023/11/25 10:33:43 in indexViewHandler()
10:33:43 | 200 | 64.652µs | 127.0.0.1 | GET | /
Now, when I invoke http://localhost:5000/about/
, the index page is rendered again while the log is:
2023/11/25 10:34:29 in pageViewHandler()
2023/11/25 10:34:29 path=pages/about
10:34:29 | 200 | 60.623µs | 127.0.0.1 | GET | /about/
which tends to show that the right handler had been called and that the right page had been rendered. But it's not the case...
If I invoke http://localhost:5000/does-not-exist/
I get a 404.
In indexViewHandler
, if I change the line return c.Render("pages/index", nil)
by return c.Render("pages/about", nil)
I still get the index page rendered!!! I believe there must be a default config somewhere but I can't figure out where.
Any help is welcome
After a full day of additional research, I found the following in the documentation:
(...) otherwise they will overwrite each other. We are living in 2023, right? How is this possible!
Anyway, the bodies of the pages were defines like this:
and the layout included them with
The variable
content
was systematically overwritten with the content of theindex
template and the same page was showing over and over again.I removed the definition of the
content
in the templates and modified the layout like this:and all works fine.
Hope this will help some lonely soul...