英文:
Golang fiber c.Render layout not excute right template
问题
我正在尝试使用一个布局和不同的模板。在layout.html
中,我有以下内容:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h1>从布局加载</h1>
{{ template . }}
</body>
</html>
在dashboard.html
中,我有以下内容:
{{ define "dashboard" }}
<h1>仪表盘</h1>
{{ end }}
在login.html
中,我有以下内容:
{{ define "login" }}
<h1>登录</h1>
{{ end }}
当我通过控制器渲染仪表盘时,它只加载login.html
,它总是加载最后一个HTML文件:
// 控制器
func Dashboard(c *fiber.Ctx) error {
return c.Render("dashboard", fiber.Map{
"title": "登录 | Selectify Admin",
}, "partials/layout")
}
在主文件中,我告诉它在哪里找到视图:
// main.go
// 创建一个新的HTML引擎
template_engine := html.New(
"./views",
".html",
)
// 创建一个新的Fiber应用程序
app := fiber.New(fiber.Config{
Views: template_engine, // 设置视图引擎
ErrorHandler: func(c *fiber.Ctx, err error) error {
return utils.HandleError(c, err)
},
})
它会报错:"template: "partials/layout" 是一个不完整或空的模板"。如何使用一个布局发送或渲染正确的HTML文件?
英文:
I'm trying to use one 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'm render dashboard through controller its only load login.html, its take last html file always
// controller
func Dashboard(c *fiber.Ctx) error {
return c.Render("dashboard", fiber.Map{
"title": "Login | Selectify Admin",
}, "partials/layout")
}
In main file I have told where to find views
//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)
},
})
it's giving an error
"template: "partials/layout" is an incomplete or empty template"
How can I send or render correct html file using one layout??
Go version 1.19
fiver version 2
"github.com/gofiber/template/html"
答案1
得分: 2
找到答案了,我们需要使用{{embed}}而不是template,这样它将包含你从控制器传递的正确模板。
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h1>从布局加载</h1>
{{ embed }}
</body>
</html>
英文:
Found the answer,
instead of template we gotta use {{embed}}, then it'll include right temlate which you pass from controller
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h1>Loaded from Layout</h1>
{{ embed }}
</body>
</html>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论