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?
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")
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With