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

问题描述 投票:1回答:2

我想在gingonic中通过c.Html()类型的Context函数传递函数。

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

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

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

html templates go go-gin
2个回答
1
投票

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

它看起来像杜松子酒框架正在创建template指针,不能被覆盖。


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")
}
© www.soinside.com 2019 - 2024. All rights reserved.