Notes

Hugo Templates in 15 Minutes

Edit on GitHub

Web Development
2 minutes

Index page

List and Single Pages

  • Menus are defined in config.toml and used in template files
  • You can define multiple different menus
  • .Site.Menus let’s you access any menu by name
 1# config.toml
 2# Site Menus
 3[menu]
 4  # Main Menu
 5  [[menu.main]]
 6    name = "Home"
 7    url = "/"
 8  [[menu.main]]
 9    name = "About"
10    identifier = "about"
11    url = "/about"
12  [[menu.main]]
13    name = "Getting Started"
14    identifier = "getting_started"
15    url = "/getting_started"
16  [[menu.main]]
17    name = "FAQs"
18    url = "/faq"
1<!-- Template -->
2{{ if .Site.Menus.main }}
3  {{ range .Site.Menus.main }}
4    <a href="{{ .URL }}">{{ .Name }}</a>
5  {{ end }}
6{{ end }}

Partials

Blocks and Base Templates

  • the base code goes in layouts/_default/baseof.html
  • it’s the template for our entire Hugo site
  • Blocks avoid copy/paste code. Instead of including the <header> and <footer> partials in every template, you can just define the new code as blocks and use the rest of the code as defined in the base template.
  • index.html and 404.html don’t use the baseof.html template
  • Blocks serve as defaults, you can overwrite them in other templates, something you can’t do with partials. For example, if you defined a code block called footer in the base template, you can override that block from any other template by defining the footer in that template
1<!-- baseof.html -->
2
3{{ block "main" . }}
4  <!-- Code goes here -->
5{{ end }}
1<!-- single.html -->
2
3{{ define "main" }}
4  <!-- Code goes here -->
5{{ end }}

Related