Hello friends! In this post, I will discuss about template functions in Beego Framework. Friends, Beego supports both custom defined function as well as built in function. First of all, let us see how we can create our own custom template function.

    In main.go, let us define a function that we want to use template function. Here, I am defining a function that will accept a number and print it like below:

func showNumber(number int) (out string) {
out = fmt.Sprintf("Entered number is: %d", number)
return
}

Then, we have to register this function to the Beego application with a name.

beego.AddFuncMap("ShowNum", showNumber)


Remember, we have to register the function before calling Run() function.


func main() {
beego.AddFuncMap("ShowNum", showNumber)
beego.Run(":8081")
}

Now, we can call this function inside the template file.

{{.Number | ShowNum}}

As the function ShowNum accepts an argument also. So, we need to pass the argument data
from controller.

c.Data["Number"] = 50
    
    The whole code will look like below:

1. default.go

func (c* MainController) Hello() {
c.Data["Number"] = 50
c.TplName = "hello.tpl"
}

2. main.go

func showNumber(number int) (out string) {
out = fmt.Sprintf("Entered number is: %d", number)
return
}

func main() {
beego.AddFuncMap("ShowNum", showNumber)
beego.Run(":8081")
}

3. hello.tpl

<div align = "middle"> <h1> Hello Beego </h1> {{.Number | ShowNum}} </div>