How to add funcmap to html template

package routes

import (
homeCtrl “aio-commerce/internal/modules/home/controllers”
“fmt”
GitHub - gin-gonic/gin: Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
“html/template”
“strconv”
)

func formatNumber(value string) string {
s, err := strconv.Atoi(value)
formatted := “”
if err == nil {
formatted = fmt.Sprintf(“%.0f”, s)
}
return formatted
}

func Routes(router *gin.Engine) {
homeController := homeCtrl.New()
router.SetFuncMap(template.FuncMap{
“formatNumber”: formatNumber,
})
router.GET(“/”, homeController.Index)
}

{{ .Title}}

{{ .ShortNotes }}

{{ formatNumber .Price }}

Hi @amansu , welcome to the forum.

The text/template documentation has a FuncMap example, does this help solving your issue?

If not, can you describe the exact problem that you observe (error messages, expected behavior versus observed behavior, etc.)?

A minimal but complete code example would also be helpful. The code as given would not compile, and it does not show how the template is executed. Ideally, the code example should run in the playground.

Also a tip: to share code in the forum, use three backticks in a separate line at the beginning and at the end of the code, like so:

    ```go
    // add go code here
    ```

Optionally, add the word go after the initial backticks, as shown.
The code will then be formatted with all indentation preserved, and with syntax highlighting applied.

error is : template: home.tmpl:52: function “formatNumber” not defined

i have made the func

//func Routes(router *gin.Engine) {
//	homeController := homeCtrl.New()
//	router.SetFuncMap(template.FuncMap{
//		"formatNumber": formatNumber,
//	})
//	router.GET("/", homeController.Index)
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.