【问题标题】:How To pass a function to template through c.HTML() in gin gonic framework (golang)如何在 gin gonic 框架(golang)中通过 c.HTML() 将函数传递给模板
【发布时间】:2016-07-06 07:03:14
【问题描述】:

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

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

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

在 html 中我们称之为{{.user}}。但是现在有了function,怎么在html模板中传递和调用呢?

【问题讨论】:

    标签: html templates go go-gin


    【解决方案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")
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2021-06-13
        • 2016-11-03
        • 2016-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-06
        • 2016-12-22
        相关资源
        最近更新 更多