Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 39 ยท Templates and Static Files

HTML Templates in Gin

Render server-side HTML pages in Gin: load templates, pass data with gin.H, use actions, loops and conditions, template functions and automatic escaping.

Not every Gin application is a JSON API. Plenty of sites render HTML on the server: admin panels, dashboards, blogs, documentation. Gin does this with Go's standard html/template package. You load a set of template files once at startup, then call c.HTML with a template name and some data. The template turns data into HTML, and, importantly, escapes it so that user input cannot inject scripts into your page.

Gin itself is not available in the in-page runner, so the Gin calls below are read-only snippets. Everything that actually produces the HTML is html/template, which Gin simply calls for you, so the runnable examples use that package directly and behave exactly like the real thing.

Loading templates and rendering a page

You load templates on the engine, before the first request, and render them from handlers.

Go
package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.LoadHTMLGlob("templates/*")

	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.tmpl", gin.H{
			"title": "Home",
			"user":  "Maya",
		})
	})
	r.Run(":8080")
}

LoadHTMLGlob("templates/*") parses every file that matches the pattern; LoadHTMLFiles("a.tmpl", "b.tmpl") lists files explicitly. The template name you pass to c.HTML is the file's base name. gin.H is just map[string]any, so any value works: strings, structs, slices, maps.

Load templates once at startup. Parsing on every request would be slow, and in release mode Gin expects you to do it up front. During development, debug mode lets you re-run the server to pick up changes (see Gin Modes and Configuration).

The template language in a nutshell

Inside a template, {{ ... }} is an action. The dot (.) is the current data. These cover most pages:

  • {{ .title }} prints a value (a map key or a struct field).
  • {{ if .user }}...{{ else }}...{{ end }} branches. Empty values ("", 0, nil, empty slice) count as false.
  • {{ range .items }}...{{ end }} loops; inside the loop the dot is the current element. Add {{ else }} for the empty case.
  • {{ with .profile }}...{{ end }} runs only when the value is non-empty and rebinds the dot.
  • {{ $name := .user }} declares a variable.
  • {{ len .items }}, {{ index .items 0 }}, {{ eq .role "admin" }}, {{ and .a .b }}, {{ not .a }} are built-in functions. Note that comparisons are functions in prefix form: eq, ne, lt, le, gt, ge.
Go A product list with if, range and else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The - in {{- and -}} trims the whitespace next to the action, which keeps generated HTML tidy. Change Products to an empty slice and run again to see the else branch of range.

Automatic escaping

html/template is context-aware. It knows whether a value lands in element text, an attribute, a URL or inside JavaScript, and escapes accordingly. This is the single most important reason to prefer it over string concatenation: stored cross-site scripting (XSS) is prevented by default.

Go Escaping in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The script tag is turned into harmless text, the query is URL-escaped inside the href, and the quotes are escaped inside the attribute. Only a value of type template.HTML skips escaping, so wrapping text in template.HTML(...) is a promise that you have already made it safe. Never wrap user input in it. If you must show user-written rich text, sanitize it with a proper HTML sanitizer first.

Template functions

Add your own helpers with FuncMap. In Gin, set them before loading the templates:

Go
r := gin.Default()
r.SetFuncMap(template.FuncMap{
	"upper": strings.ToUpper,
	"money": func(cents int) string { return fmt.Sprintf("$%d.%02d", cents/100, cents%100) },
	"date":  func(t time.Time) string { return t.Format("2 Jan 2006") },
})
r.LoadHTMLGlob("templates/*")

Then {{ money .Price }} or {{ .Name | upper }} work in templates. The pipe passes the left value as the last argument of the function on the right.

Go Custom functions with FuncMap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Keep functions small and pure. Formatting belongs in templates; business logic does not.

Passing data well

Prefer typed view models over giant gin.H maps once a page grows: a struct documents what the page needs and the compiler catches typos in Go code (the template still resolves field names at run time, so a mistyped field fails when the page renders, not when you build). Remember that only exported struct fields (capitalized) are visible to templates. A missing map key prints <no value> by default; set Option("missingkey=error") on a plain template to make it an error.

Errors inside a template are hard to recover from halfway through a response. Test every page, which you will learn in Testing Gin Handlers, and render pages into a buffer first if you need to avoid half-written output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which package does Gin use to render HTML?

    Gin delegates to html/template, which escapes values depending on where they appear in the page.
  2. 2. What does {{ range .items }}{{ else }}...{{ end }} do with an empty slice?

    The else branch of range runs when there is nothing to iterate over.
  3. 3. A user submits a comment containing a script tag. What happens if you print it with {{ .Comment }}?

    html/template escapes it, so it appears as visible text and cannot execute.
  4. 4. When must you call SetFuncMap relative to LoadHTMLGlob?

    A template that calls an unknown function fails to parse, so the functions must be registered first.
  5. 5. Which struct fields can a template read?

    Templates use reflection, which can only see exported fields.

Summary

  • Load templates once with LoadHTMLGlob or LoadHTMLFiles, render with c.HTML(status, name, data).
  • Actions: {{ .x }}, if, range, with, variables, and prefix comparison functions like eq and lt.
  • html/template escapes by context; only template.HTML and friends bypass it, so never wrap untrusted text.
  • Register helpers with SetFuncMap before loading; use typed view models for larger pages.

Next: Layouts, Partials and Template Inheritance