如何在 gin Gonic 框架 (golang) 中通过 c.HTML() 将函数传递给模板

Vut*_*tuz 5 html templates go go-gin

我想通过gingonicc.Html()类型的函数传递一个函数Context

例如,如果我们想传递一个变量,我们使用

    c.HTML(http.StatusOK, "index", gin.H{
        "user":   user,
        "userID": userID,
    })
Run Code Online (Sandbox Code Playgroud)

在 html 中,我们将其称为{{.user}}. 但是现在,有了函数,我们如何在html模板中传递和调用它呢?

rco*_*rre 8

现在可以使用Engine.SetFuncMap. 自述文件现在包括以下示例

import (
    "fmt"
    "html/template"
    "net/http"
    "time"

    "github.com/gin-gonic/gin"
)

func formatAsDate(t time.Time) string {
    year, month, day := t.Date()
    return fmt.Sprintf("%d%02d/%02d", year, month, day)
}

func main() {
    router := gin.Default()
    router.Delims("{[{", "}]}")
    router.SetFuncMap(template.FuncMap{
        "formatAsDate": formatAsDate,
    })
    router.LoadHTMLFiles("./fixtures/basic/raw.tmpl")

    router.GET("/raw", func(c *gin.Context) {
        c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{
            "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
        })
    })

    router.Run(":8080")
}
Run Code Online (Sandbox Code Playgroud)


MIk*_*ode 2

为了在模板中创建函数,您需要创建新的FuncMap

看起来 gin 框架正在创建模板指针并且不能被覆盖。