Lesson Overview

Template Syntax

Everything you need to know about Hugo's Template Syntax.
3 minutes 428 words

Basics

Hugo templates are HTML files that have extra syntax added to them to make them more dynamic.

It allows us to have HTML code generated for us based on content, instead of having to write code manually for every post.

The way to access Hugo’s special features inside of an HTML file, all we need to write is {{ }} and inside those curly braces we write Hugo code.

Variables

Hugo injects a bunch of useful variables into templates depending on what kind of template is currently being shown on screen.

The way to access these variables are by adding the curly braces and then a dot with the variable name, like this: {{ .VariableNameHere }}. We will often write code like this: <title>{{ .Title }}</title> to set our page tab title dynamically.

We will see this syntax often in the next sections, it is vital to Hugo.

We will go over all the important variables injected in later sections.

Functions

Hugo also provides many functions that we can use inside our templates. Functions are different from variables because they change the output based on the input.

For example, if we use the add function, <p>{{ add 1 2 }}</p> then the output would be <p>3</p> and the output would change depending on the numbers we input. This is different than variables because variables do not change based on input because there are no inputs for variables.

Logic

Hugo allows basic logic based operators in templates, such as if statements and loops.

Conditionals

Hugo gives us a few special operators for performing conditional rendering. if, else, with, or and and, are each used for deciding what elements to render in our template.

There are many different ways to use those operators, full documentation can be found here, but we will also see many examples throughout the rest of this course.

Loops

Loops are an important feature of any programming language or framework. It allows the reuse of logic for many items.

We can loop over data injected into the templates by Hugo, using the range operator, such as a list of pages or a list of tags or categories.

<ul>
{{ range $list }}
    <li>{{ . }}</li> <!-- The . represents an element in $list variable -->
{{ end }}
</ul>

Output of the above would be:

<!-- This output assumes the $list variable held 3 items with the text below-->
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

This is the majority that we need to know about Hugo templates to continue with the next sections.

Share this page