Golang Fiber is a high-performance web framework that is widely used in Go language development. However, sometimes when using Fiber to render a layout, you may encounter problems where the template is not executed correctly. This may be due to a bug in the code or a configuration issue. In this article, PHP editor Apple will analyze this problem in detail and provide solutions to help you overcome this challenge. Whether you are a beginner or an experienced developer, you can get useful knowledge and skills from this article to improve your capabilities in Golang Fiber development.
I'm trying to use a layout with different templates,
├── main folder ├── cmd └── main.go ├── controllers ├── models ├── views └── partials └── layout.html └── index.html └── dashboard.html └── login.html └── public └── sample.png
In my layout.html
I have
<!doctype html> <html lang="en"> <head> </head> <body> <h1>loaded from layout</h1> {{ template . }} </body> </html>
In my dashboard.html
{{ define "dashboard" }} <h1>dashboard</h1> {{ end }}
In my login.html
{{ define "login" }} <h1>login</h1> {{ end }}
When I render the dashboard through the controller, it only loads login.html, it always gets the last html file
// controller func dashboard(c *fiber.ctx) error { return c.render("dashboard", fiber.map{ "title": "login | selectify admin", }, "partials/layout") }
In the main file I have told where to find the view
//main.go // create a new HTML engine template_engine := html.New( "./views", ".html", ) // create a new Fiber app app := fiber.New(fiber.Config{ Views: template_engine, // set the views engine ErrorHandler: func(c *fiber.Ctx, err error) error { return utils.HandleError(c, err) }, })
An error occurred "Template: 'partials/layout' is an incomplete or empty template" How to send or render correct html file using one layout?
go version 1.19 fifth edition 2 "github.com/go fiber/template/html"
Find the answer, We have to use {{embed}} instead of template, then it will contain the correct template that you pass from controller
<!DOCTYPE html> <html lang="en"> <head> </head> <body> <h1>Loaded from Layout</h1> {{ embed }} </body> </html>
The above is the detailed content of Golang Fiber c. Rendering layout does not enforce correct templates. For more information, please follow other related articles on the PHP Chinese website!