Golang Gin中间件传递数据给模板

huangapple go评论89阅读模式
英文:

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 (
	&quot;html/template&quot;
	&quot;log&quot;
	&quot;strconv&quot;

	&quot;github.com/gin-gonic/gin&quot;
)

type User struct {
	Username string

	Age int
}

func setUser(u *User) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// u.Age = 100
		// u.Username = &quot;Default&quot;
		if s, b := ctx.GetQuery(&quot;username&quot;); b {
			u.Username = s
		}
		if s, b := ctx.GetQuery(&quot;age&quot;); b {
			i, err := strconv.Atoi(s)
			if err != nil {
				panic(err.Error())
			}
			u.Age = i
		}
	}
}

var user = &amp;User{&quot;Default&quot;, 100}

func GetUsername() string {
	return user.Username
}

func GetAge() int {
	return user.Age
}

func main() {
	r := gin.New()

	r.SetFuncMap(template.FuncMap{
		&quot;Username&quot;: GetUsername,
		&quot;Age&quot;:      GetAge,
	})
	r.LoadHTMLGlob(&quot;*.tmpl&quot;)

	r.GET(&quot;/&quot;, setUser(user), func(ctx *gin.Context) {
		data := map[string]interface{}{
			&quot;title&quot;: &quot;Learning Golang Web&quot;,
			&quot;name&quot;:  &quot;Batman&quot;,
		}

		ctx.HTML(200, &quot;index.tmpl&quot;, data)
	})

	log.Fatalln(r.Run())
}

index.tmpl

&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;{{.title}}&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;p&gt;Welcome {{.name}}&lt;/p&gt;
    &lt;p&gt;Your Username is {{ Username }}&lt;/p&gt;
    &lt;p&gt;Your Age is {{ Age }}&lt;/p&gt;
  &lt;/body&gt;
&lt;/html&gt;

if you go to http://localhost:8080/?username=admin&amp;age=50 it will show different display

huangapple
  • 本文由 发表于 2022年2月23日 07:12:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/71229454.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定