Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
02 Sep 2023 · 3 min read ·Article 40 / 119
Go

10 How to Understanding HTML Template Data in Golang

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

Introduction to Data Templates

If you have studied HTML Templates in the previous article, then we will continue with data templates where we can display this data dynamically by using struct or map data. However, we need to know the changes in the template text. We need to know the name of the field or key that we will use to fill in the dynamic data in the template. We can mention the name of the field or key, for example {{.FieldName}}.

Apply to Project Handler

We first create a template in the templates folder by creating a new file name.html with contents as follows.

html
 1<!DOCTYPE html>
 2<html lang="en">
 3  <head>
 4    <meta charset="UTF-8">
 5    <title>{{ .Title }}</title>
 6  </head>
 7  <body>
 8    <h1>Hello {{ .Name }}</h1>
 9  </body>
10</html>

If we look at the HTML code above, it is very simple, we will send the Title and Name data from the handler to the HTML template. Next, we create a handler function as below.

go
1func TemplateDataStructHandler(w http.ResponseWriter, r *http.Request) {
2	t := template.Must(template.ParseFiles("./templates/name.html"))
3	t.ExecuteTemplate(w, "name.html", map[string]interface{}{
4		"Title": "Template Data Struct",
5		"Name":  "Santekno",
6	})
7}

If you want to use struct, the difference is actually the same, namely that we send the template a struct which we have defined as in the example below.

go
 1type Page struct {
 2	Title string
 3	Name  string
 4}
 5
 6func TemplateDataStructHandler(w http.ResponseWriter, r *http.Request) {
 7	t := template.Must(template.ParseFiles("./templates/name.html"))
 8	t.ExecuteTemplate(w, "name.html", Page{
 9		Title: "Template Data Struct",
10		Name:  "Santekno",
11	})
12}

And don’t forget to also add the handler function to initiate mux with a different endpoint like this.

go
1mux.HandleFunc("/template-data-map", TemplateDataMapHandler)
2mux.HandleFunc("/template-data-struct", TemplateDataStructHandler)

So we can run our program then open the browser and access this endpoint, then a page will appear with the title Data Struct Template and an HTML tag called Santekno.

bash
1http://localhost:8080/template-data-struct
2http://localhost:8080/template-data-map

HTML Template Testing

The way we test the handler function that we have created is by using a unit test as below.

go
 1func TestTemplateDataMapHandler(t *testing.T) {
 2	tests := []struct {
 3		name string
 4		want string
 5	}{
 6		{
 7			name: "get from embed",
 8			want: "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\">\n    <title>Template Data Map</title>\n  </head>\n  <body>\n    <h1>Hello Santekno</h1>\n  </body>\n</html>",
 9		},
10	}
11	for _, tt := range tests {
12		t.Run(tt.name, func(t *testing.T) {
13			request := httptest.NewRequest(http.MethodGet, "http://localhost/file", nil)
14			recorder := httptest.NewRecorder()
15			TemplateDataMapHandler(recorder, request)
16
17			body, _ := io.ReadAll(recorder.Result().Body)
18			bodyString := string(body)
19
20			if !reflect.DeepEqual(bodyString, tt.want) {
21				t.Errorf("response = %#v, want = %#v\n", bodyString, tt.want)
22			}
23		})
24	}
25}
26
27func TestTemplateDataStructHandler(t *testing.T) {
28	tests := []struct {
29		name string
30		want string
31	}{
32		{
33			name: "get from embed",
34			want: "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\">\n    <title>Template Data Struct</title>\n  </head>\n  <body>\n    <h1>Hello Santekno</h1>\n  </body>\n</html>",
35		},
36	}
37	for _, tt := range tests {
38		t.Run(tt.name, func(t *testing.T) {
39			request := httptest.NewRequest(http.MethodGet, "http://localhost/file", nil)
40			recorder := httptest.NewRecorder()
41			TemplateDataStructHandler(recorder, request)
42
43			body, _ := io.ReadAll(recorder.Result().Body)
44			bodyString := string(body)
45
46			if !reflect.DeepEqual(bodyString, tt.want) {
47				t.Errorf("response = %#v, want = %#v\n", bodyString, tt.want)
48			}
49		})
50	}
51}

In this unit test we ensure that the input sent from the handler matches the HTML template response sent.

Related Articles

💬 Comments