Basic Hugo Template Syntax

Hugo uses Go’s html/template and text/template libraries as its template foundation.

This is only an introduction to Go templates. For details about Go templates, see the official Go documentation.

Go templates provide a simple template language based on the idea that only basic logic should be reflected in the template or view layer.

Basic Syntax

Go templates are HTML made up of variables and functions. To use variables and functions in Go templates, use {{ }}.

{{ .Title }}
{{ $address }}
  • .Title is a predefined variable.
  • $address is a custom variable.

Function arguments are separated by spaces.

{{ FUNCTION ARG1 ARG2 }}
{{ add 1 2 }}

Use a dot (.) to access methods and fields, such as page parameters defined in front matter.

{{ .Params.bar }}

Parentheses can be used to group items, and a single statement can be split over multiple lines.

{{ if or (isset .Params "alt") (isset .Params "caption") }} Caption {{ end }}

Variables

Each Go template receives a data object. In Hugo, each template receives a Page. Because Page is the default scope, elements such as .Title can be accessed with the . prefix.

<title>{{ .Title }}</title>

Custom variables must use the $ prefix.

{{ $address := "123 main st." }}
{{ $address }}

The = operator can assign a new value to a variable.

{{ $var := "Hugo Page" }}
{{ if .IsHome }}
    {{ $var = "Hugo Home" }}
{{ end }}
Var is {{ $var }}

Functions

Go templates provide only a few basic functions, but Hugo adds many template functions. Functions are called by name, and required arguments are separated by spaces.

{{ add 1 2 }}
{{ lt 1 2 }}

Includes

When including another template, pass the data that should be available inside it. To pass the current context, add a trailing dot (.).

{{ partial "header.html" . }}
{{ template "_internal/opengraph.html" . }}

Template paths start from Hugo’s layouts/ directory. partial is used to include separated templates, while template is now mainly used for internal Hugo templates.

Logic

Go templates provide basic loops and conditionals. range iterates through maps, arrays, and slices.

{{ range $array }}
    {{ . }}
{{ else }}
    <!-- This is evaluated only if $array is empty -->
{{ end }}

if, else, with, or, and, and not provide conditional logic. Go templates treat false, zero, and zero-length arrays, slices, maps, or strings as false.

{{ with .Params.title }}
    {{ . }}
{{ end }}

This page summarizes the basic syntax needed to read and write Hugo templates.