Watch on Youtube: Parsing Different Types of Data to the Template in Beego Framework
Hello friends! In this post, I will discuss about how to parse different data types into template in Beego application. Friends, when are a developing a full stack web application, then many times, we need to pass collection of data. In Golang, we generally deal with three group of data:
a. struct
b. map
c. slice
In this post, I will show you how we can pass these data types into the template. Let us start with struct.
First of all, in the controller file, let us create a struct Person.
Now, let us define a controller function hello() like below:
func (c* MainController) Hello() {}
We will assign some values to the struct Product and pass them through
this Hello() function.
After this, we will render a template file through this function:
c.TplName = "hello.tpl"
The whole controller code is like below:
Now, we have to create a template file inside the view directory.
We have to name it as: hello.tpl.
We will retrieve the data in this template file that we are sending from
controller function.
That's it guys. Now start your application using bee run command and hit
the url. You will be able to see the struct data.
Similarly, you can parse map data and slice data. Let us see how we can
parse map data. In the Hello() function itself, add below code to create
a map and parse it:
mp := map[string]interface{} {
We can retrieve above map data in template file like below:
Now, to parse slice, add below code in Hello() function:
Add below code in template file to get above mentioned slice data:
The whole code is like below: