Rendering the about page from the server side

Now that we've seen how the server-side application transmits the template bundle to the client-side application, let's take a look at the AboutHandler function found in the about.go source file in the handlers folder. This is the server-side handler function that is responsible for rendering the About page:

func AboutHandler(env *common.Env) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gophers := env.DB.GetGopherTeam()
templateData := templatedata.About{PageTitle: "About", Gophers: gophers}
env.TemplateSet.Render("about_page", &isokit.RenderParams{Writer: w, Data: templateData})
})
}

The AboutHandler function has three responsibilities:

  • Fetching the gophers from the datastore
  • Creating the template data object
  • Rendering the About page template

The first line of code, defined in the function, fetches the gopher objects from the datastore, where a gopher object represents an individual gopher team member. In our sample data set, there are three gophers: Molly, Case, and Wintermute.

The second line of code is used to set up the template data object of the templatedata.About type. This is the data object that will be fed into the template. The PageTitle property of the data object is used to display the page title, and we will populate the Gophers property of the object with the slice of gopher objects that are retrieved from the datastore.

In the third, and final line of the handler function, we call the Render method of the template set to render the template. The first parameter passed to the method is the name of the template to be rendered. In this case, we have specified that we want to render the about_page template. Take note that this is a page template that will not only render the About page content but also the entire web page layout, which in addition to the primary content area section will also include the header, the top bar, the navigation bar, and the footer areas of the web page.

The second parameter to the function is the template render parameters (isokit.RenderParams). We have populated the Writer field, with http.ResponseWriter, w. Also, we have populated the Data field, which represents the data object that should be supplied to the template with the templateData object that we had just created.

That's all there is to it. Now we can render this template on the server side. We have now implemented the classic web application architecture flow where the entire web page is rendered from the server side. We can access the About page at http://localhost:8080/about. Here's how the About page looks rendered from the server side:

Figure 4.5 The About page rendered from the server side
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.50.156