Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To pass a function to template through c.HTML() in gin gonic framework (golang)

I want to pass a function through c.Html() function of type Context in gingonic.

For example, if we want to pass a variable, we use

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

And in html we call it as {{.user}}. But now, with function, how can we pass and call it in html template?

like image 734
Vutuz Avatar asked Jul 06 '16 07:07

Vutuz


2 Answers

This is now possible using Engine.SetFuncMap. The readme now includes the following 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")
}
like image 162
rcorre Avatar answered Sep 22 '22 07:09

rcorre


In order to create function in a template you need to create new FuncMap

It`s look like the gin framework is creating the template pointer and cannot be overwritten.

like image 39
MIkCode Avatar answered Sep 21 '22 07:09

MIkCode