Variables

Hugo's layouts system allows you to do simple programming inside a template. In this case, we can start with variables. Hugo make uses of the native Go html/template to make its layouts system working. That also means we have data types, values and management to deal with if we are programming inside layouts template.

The good news is, for Hugo, you don't need to worry complicated or logical blocks thanks to its static sites generations.

If you want to build a Go compatible theme module, then you need to be careful with logic complications for performance.

Create

To create variable, it simply complies to Go variable system. You need to know what types of data before you create one. All newly born variables must be created using the := symbol, aligning to Go variable system. There is only 1 difference from normal Go source code: each variable is accompanied by a dollar sign. Example:

{{- $variable := "Hello World" -}}

Otherwise, you will break the template system.


String

To create a string, simple set it to empty string, example:

{{- $myString := "A quick brown fox jumps over the lazy dog." -}}


Integer / Number

To create an integer, set it to 0:

{{- $myLuckyNumber := 0 -}}


Array

To create an array (usually string), you use the slice function without any values:

{{- $myArray := slice -}}

Keep in mind that array in template system is very limited so play it wisely.

Read

Using the variable is straight-forward like any languages. The only thing you need to remember is to include the dollar sign in the name.

Normal Printout

to printout, just call it out:

{{- $myVariable -}}

This will print out only the value in the variable.

If you want the spacing before and after the value, remove the hyphen at the double curly braces (it means trim whitespace at that side). Example, to trim only the left side whitespace, it is:

{{ $myVariable -}}


Apply to Function

Another way to read (or use) the variable is to apply it into a function. Example, appending a variable into an array using append function.

{{- $myArray := slice -}}
{{- $myString = "A string" -}}
{{- $myArray = $myArray | append $myString -}}


Apply to Partials

Applying a variable into a partial layout requires the use of dictionary function (dict). Example:

{{ partial "links/absLangLink" (dict "context" . "data" $myString) }}

Then inside the partial, you call it out like the way you use a normal variable. Example:

{{- $context := .context -}}
{{- $data := .data -}}
...

Update

Updating a variable's is simply setting a new value with equal sign. Example:

{{- $myString := "Old String" -}}
{{- $myString = "Update to New String" -}}

Some variables are restricted so you are not allowed to alter them.

Delete

Unfortunately, this is not available due to Go language. All variables will be garbage collected at the end of its operations so you don't need to do that explicitly.

That's all about variables in Hugo Layout and Go Template.