Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 39 ยท Templates and Static Files

Layouts, Partials and Template Inheritance in Gin

Share one page layout across many Gin pages with define, template and block, reuse partials, and avoid the name clash that LoadHTMLGlob causes. Runnable stand-ins.

A real site has a header, a navigation bar and a footer on every page. Copying them into each template is a maintenance trap: change the menu and you edit twenty files. Go templates solve this with named templates: you define a layout once and let each page fill in the parts that differ. Gin inherits all of this from html/template, with one Gin-specific catch about how templates are loaded, which this lesson explains.

Remember the rule from the previous lesson, HTML Templates in Gin: the examples you can run here are stand-ins that use html/template directly, and the Gin calls are read-only snippets.

Named templates: define and template

{{ define "name" }}...{{ end }} creates a named template. {{ template "name" . }} inserts it, passing the data (the final dot) along. Think of them as functions for HTML.

Go A reusable partial

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.

Partials are the building blocks: a navigation bar, a product card, a form field, a flash message. Each one is a define block you pass the exact data it needs.

Layout with block

For whole pages, use {{ block "content" . }}default{{ end }} in the layout. A block is a define plus an immediate template call: it shows the default content unless a page redefines it. A page then overrides only what it needs.

HTML
<!-- templates/layout.tmpl -->
{{ define "layout" }}
<!doctype html>
<html lang="en">
<head><title>{{ block "title" . }}My site{{ end }}</title></head>
<body>
  {{ template "nav" . }}
  <main>{{ block "content" . }}{{ end }}</main>
</body>
</html>
{{ end }}
HTML
<!-- templates/about.tmpl -->
{{ define "title" }}About{{ end }}
{{ define "content" }}<h1>About us</h1>{{ end }}

The Gin catch: one global namespace

LoadHTMLGlob("templates/*") parses every file into one template set. All define names share one namespace, and when two files both define content, the last one parsed wins for every page. So with the files above and a second page contact.tmpl that also defines content, every URL would show the same content. This is the number one surprise for newcomers to Gin templates.

You have three clean ways out:

  1. Unique names per page. Define about.content, contact.content, and have each page call its own. Simple, a little verbose.
  2. One template set per page. Parse layout.tmpl together with exactly one page file for each page. The official extension github.com/gin-contrib/multitemplate does this and plugs into r.HTMLRender.
  3. Avoid inheritance. Render the page template, which itself calls {{ template "header" . }} and {{ template "footer" . }}.

A multitemplate setup looks like this (read-only, it needs the extension module):

Go
func createRenderer() multitemplate.Renderer {
	r := multitemplate.NewRenderer()
	r.AddFromFiles("about", "templates/layout.tmpl", "templates/about.tmpl")
	r.AddFromFiles("contact", "templates/layout.tmpl", "templates/contact.tmpl")
	return r
}

router := gin.Default()
router.HTMLRender = createRenderer()
router.GET("/about", func(c *gin.Context) {
	c.HTML(http.StatusOK, "about", gin.H{"title": "About"})
})

Proving the clash, and the fix

This stand-in does exactly what Gin does in the two cases. First all files in one set, then one set per page:

Go Shared namespace versus one set per page

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.

In the first line both pages would show "Contact page". With separate sets each page gets its own content.

Passing layout data

A layout often needs shared data (the current user, a flash message, the page title) on top of the page's own data. Do not stuff everything into a map in every handler. Write one small helper that builds the common part and merges the page data:

Go
func page(c *gin.Context, extra gin.H) gin.H {
	data := gin.H{
		"user":  c.GetString("user"), // set by an auth middleware
		"year":  time.Now().Year(),
	}
	for k, v := range extra {
		data[k] = v
	}
	return data
}

r.GET("/about", func(c *gin.Context) {
	c.HTML(http.StatusOK, "about", page(c, gin.H{"title": "About"}))
})

The middleware that sets user is covered in the Middleware chapter and in JWT Authentication. The idea: middleware prepares request-scoped values with c.Set, the helper reads them with c.Get.

Try it: a mini site with a shared navigation

This example builds a three-page site on a mux and requests each page. The navigation highlights the current page, a classic partial with a condition.

Go Three pages, one layout, active menu item

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.

Common mistakes

  • Defining content in several files and loading them all with one glob (use unique names or per-page sets).
  • Forgetting the dot: {{ template "nav" }} passes nil, so the partial sees no data. Write {{ template "nav" . }}.
  • Using {{ .Path }} inside a range where the dot has changed. Use $.Path to reach the root data.
  • Putting logic into templates. Keep decisions in Go and let templates display values.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does {{ template "nav" . }} do?

    template calls an already defined template. The trailing dot passes the current data; without it the partial receives nil.
  2. 2. Two files loaded with one LoadHTMLGlob both define content. What happens?

    All files share one namespace and later definitions replace earlier ones, so every page ends up showing the same content block.
  3. 3. How do you reach the top-level data inside a {{ range }} where the dot has changed?

    $ always refers to the data that was passed to Execute, even inside range or with.
  4. 4. What is the role of multitemplate in Gin?

    gin-contrib/multitemplate lets you register layout plus page files per page name and assign the result to r.HTMLRender.

Summary

  • define creates a named template, template inserts it, block is define plus default content.
  • A layout defines the frame; pages override named blocks.
  • LoadHTMLGlob merges all files into one namespace, so duplicate define names clash; use unique names or one set per page (multitemplate).
  • Build shared layout data in one helper instead of repeating it in every handler.
  • Pass the dot to partials and use $ inside range.

Next: Static Files and Embedding Assets