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

时间:2016-07-06 07:03:15

标签: html templates go go-gin

我希望通过gingonic中c.Html()类型的Context函数传递一个函数。

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

    c.HTML(http.StatusOK, "index", gin.H{
        "user":   user,
        "userID": userID,
    })

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

2 个答案:

答案 0 :(得分:1)

要在模板中创建功能,您需要创建新的FuncMap

看起来像gin框架正在创建template指针并且无法覆盖。

答案 1 :(得分:1)

现在可以使用Engine.SetFuncMap。 自述文件现在包含以下example

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")
}