2. Handling HTTP Requests with Gin – Gin Template Engine

2.6.3 Gin Template Engine

    Gin supports rendering various data formats, including <span>JSON</span>, <span>XML</span>, <span>HTML</span>, etc. Among these, rendering HTML templates is very common in web development, and Gin provides a very convenient way to load and render HTML templates.

    Gin uses the <span>html/template</span> package to render templates, and the process consists of three steps:

  • Loading templates: Load template files using the <span>LoadHTMLFiles()</span> or <span>LoadHTMLGlob()</span> methods.
  • Defining route handler functions: Use the <span>HTML()</span> method in the route to render the template.
  • Passing data: Pass data to the template by providing a map or struct.

2.6.3.1 Loading Template Files

    Gin provides two methods for loading template files:

  • <span>LoadHTMLFiles()</span>: Load files individually.
  • <span>LoadHTMLGlob()</span>: Load files in bulk based on path matching rules.

    The example code is as follows:

package main

import (
 "net/http"
 "github.com/gin-gonic/gin"
)

func main() {
 r := gin.Default()
 // Load one or more template files
 // r.LoadHTMLFiles("templates/index.html", "templates/ol.html")
 // Load all template files in the specified directory
 r.LoadHTMLGlob("templates/*")

 r.GET("/load_html", func(ctx *gin.Context) {
  // Render the template file
  ctx.HTML(http.StatusOK, "index.html", gin.H{
   "body": "Gin renders HTML example",
  })
 })

 r.GET("ol_html", func(ctx *gin.Context) {
  // Render the template file
  ctx.HTML(http.StatusOK, "ol.html", gin.H{
   "body": "Gin renders HTML example",
  })
 })

 r.Run(":8080")
}

    In the above code, <span>LoadHTMLFiles()</span> is used to load the template files index.html and ol.html, while <span>LoadHTMLGlob()</span> loads all template files in the specified directory <span>templates</span>. The <span>HTML()</span> method in the route handler function is used to render the HTML page, with the basic syntax as follows:

ctx.HTML(httpStatusCode, "templateName", gin.H{
   "key": value,
})
  • The first parameter is the HTTP status code.
  • The second parameter is the name of the template file.
  • The third parameter is the data passed to the template, which can be a map or struct.

    In the template, you can reference the passed variables using the <span>{{}}</span> syntax, as shown in the following example:

{{define "ol.html" }}
    &lt;br&gt;
 &lt;!-- Reference variable, using the value of key 'body' from the map --&gt;
    &lt;h1&gt;{{ .body }}&lt;/h1&gt;
    &lt;ol&gt;
        &lt;li&gt;Monday&lt;/li&gt;
        &lt;li&gt;Tuesday&lt;/li&gt;
        &lt;li&gt;Wednesday&lt;/li&gt;
        &lt;li&gt;Thursday&lt;/li&gt;
        &lt;li&gt;Friday&lt;/li&gt;
    &lt;/ol&gt;
{{ end  }}

    Gin supports template nesting, allowing you to define a main template to nest content across different pages. An example is shown below:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8"&gt;
        &lt;title&gt;&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;br&gt;
        &lt;h1&gt;{{ .body }}&lt;/h1&gt;
        &lt;hr&gt;
        {{ template "ul.html" }}
        &lt;hr&gt;
        {{ template "ol.html" }}
    &lt;/body&gt;
&lt;/html&gt;

{{define "ul.html" }}
    &lt;h1&gt;ul.html demonstration example&lt;/h1&gt;
    &lt;ul&gt;
        &lt;li&gt;Monday&lt;/li&gt;
        &lt;li&gt;Tuesday&lt;/li&gt;
        &lt;li&gt;Wednesday&lt;/li&gt;
        &lt;li&gt;Thursday&lt;/li&gt;
        &lt;li&gt;Friday&lt;/li&gt;
    &lt;/ul&gt;
{{ end  }}

    In addition to using a map to pass data, you can also use a struct to pass data, which allows for better type checking. The example code is as follows:

type Person struct {
 Name     string
 Age      int
 Location string
}

r.GET("person_html", func(ctx *gin.Context) {
 // Render the template file
 ctx.HTML(http.StatusOK, "person.html", Person{
  Name:     "Surpass",
  Age:      rand.Intn(100),
  Location: "China",
 })
})

2.6.3.2 Loading Static Files

    When using templates, it is often necessary to provide static files, such as CSS and JavaScript. Gin provides the <span>Static()</span> method to handle and load static files, defined as follows:

func (group *RouterGroup) Static(relativePath, root string) IRoutes

router.Static(“/static”, “/var/www”) maps the /static directory to the /var/www directory in the file system.

    Gin caches template files in memory by default. If developers modify the template files, they need to restart the application to see the changes. The default delimiter in Gin is <span>{{}}</span>, and if there are conflicts, you can also use <span>Delims()</span> to customize the delimiters to avoid conflicts.

Leave a Comment