英文:
Golang Gin Middleware pass Data to Template
问题
你好,目前我正在做一个小项目,有一个问题想问。
有没有办法从中间件将数据传递给模板?
例如:
func CheckAuth(c *gin.Context) { //这个中间件从会话中获取用户并将其传递给模板
session := sessions.Default(c)
user := session.Get(userkey)
// 通过id = user从数据库中获取用户
var account models.Account
if err := models.DB.Where("id = ?", user).First(&account).Error; err != nil {
_ = 1
}
// 将account传递给每个模板
c.Next()
}
原因是我在布局中使用了用户,并且需要检查他的用户名或者他是否为空等等,每个函数都进行传递感觉不太对劲。我知道Laravel有类似的功能。
我正在使用c.HTML
来显示HTML文件。
提前感谢!
英文:
Hi currently i am doing a little project and i have question.
Is there a way to pass Data to a template from a Middleware?
For Example:
func CheckAuth(c *gin.Context) { //This Middleware gets the user from the session and passes it to the template
session := sessions.Default(c)
user := session.Get(userkey)
// Get if possible the user from the database with id = user
var account models.Account
if err := models.DB.Where("id = ?", user).First(&account).Error; err != nil {
_ = 1
}
// pass the account into every temaplte
c.Next()
The reason is that i use the user in my layout and have to check his username or if he is just nil etc and doing the pass in every functions feels wrong?
I know Laravel has something like this.
I am using the c.HTML to display the html file
Thanks in advance!
答案1
得分: 1
你可以使用SetFuncMap或FuncMap在模板中创建自定义函数。
在调用LoadHTMLFiles或LoadHTMLGlob之前,必须设置它。
中间件用于控制值,例如:结构体
以下是示例代码:
main.go
package main
import (
"html/template"
"log"
"strconv"
"github.com/gin-gonic/gin"
)
type User struct {
Username string
Age int
}
func setUser(u *User) gin.HandlerFunc {
return func(ctx *gin.Context) {
if s, b := ctx.GetQuery("username"); b {
u.Username = s
}
if s, b := ctx.GetQuery("age"); b {
i, err := strconv.Atoi(s)
if err != nil {
panic(err.Error())
}
u.Age = i
}
}
}
var user = &User{"Default", 100}
func GetUsername() string {
return user.Username
}
func GetAge() int {
return user.Age
}
func main() {
r := gin.New()
r.SetFuncMap(template.FuncMap{
"Username": GetUsername,
"Age": GetAge,
})
r.LoadHTMLGlob("*.tmpl")
r.GET("/", setUser(user), func(ctx *gin.Context) {
data := map[string]interface{}{
"title": "Learning Golang Web",
"name": "Batman",
}
ctx.HTML(200, "index.tmpl", data)
})
log.Fatalln(r.Run())
}
index.tmpl
<!DOCTYPE html>
<html>
<head>
<title>{{.title}}</title>
</head>
<body>
<p>Welcome {{.name}}</p>
<p>Your Username is {{ Username }}</p>
<p>Your Age is {{ Age }}</p>
</body>
</html>
如果你访问 http://localhost:8080/?username=admin&age=50
,它将显示不同的内容。
英文:
You can use SetFuncMap or FuncMap to create custom functions on templates.
> You must set it before calling LoadHTMLFiles or LoadHTMLGlob.
Middleware is for control value, ie: struct
This is the example
main.go
package main
import (
"html/template"
"log"
"strconv"
"github.com/gin-gonic/gin"
)
type User struct {
Username string
Age int
}
func setUser(u *User) gin.HandlerFunc {
return func(ctx *gin.Context) {
// u.Age = 100
// u.Username = "Default"
if s, b := ctx.GetQuery("username"); b {
u.Username = s
}
if s, b := ctx.GetQuery("age"); b {
i, err := strconv.Atoi(s)
if err != nil {
panic(err.Error())
}
u.Age = i
}
}
}
var user = &User{"Default", 100}
func GetUsername() string {
return user.Username
}
func GetAge() int {
return user.Age
}
func main() {
r := gin.New()
r.SetFuncMap(template.FuncMap{
"Username": GetUsername,
"Age": GetAge,
})
r.LoadHTMLGlob("*.tmpl")
r.GET("/", setUser(user), func(ctx *gin.Context) {
data := map[string]interface{}{
"title": "Learning Golang Web",
"name": "Batman",
}
ctx.HTML(200, "index.tmpl", data)
})
log.Fatalln(r.Run())
}
index.tmpl
<!DOCTYPE html>
<html>
<head>
<title>{{.title}}</title>
</head>
<body>
<p>Welcome {{.name}}</p>
<p>Your Username is {{ Username }}</p>
<p>Your Age is {{ Age }}</p>
</body>
</html>
if you go to http://localhost:8080/?username=admin&age=50
it will show different display
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论