Templates cheat sheet

Quick overview of Hugo templates.

Hugo Templates

Variables

Custom Variables
{{$mycustom := site.Title}} Site Title: {{$mycustom}}
{{/* Override $mycustom */}} {{$mycustom = .Page.Title}} Page Title: {{$mycustom}}

Data Types
Integer: {{2}}
Float: {{3.14}}
Boolean: {{false}}
String: {{"hello"}}

Slice: {{slice "foo" "bar" "buzz"}}
Dict: {{dict "key1" "val1" "w" 10 "h" 20}}
Time: {{time "2020-01-01T00:00:00+08:00"}}

{{ $scratch := newScratch }} {{ $scratch.Set "message" "Hello" }} Scratch: {{ $scratch }}
Getter: {{ $scratch.Get "message" }}
{{/* Appends a string, adds a number, inserts in a slice */}} {{ $scratch.Add "message" " World" }} Updated: {{$scratch.Get "message"}}
{{ $scratch := newScratch }} {{/* You can also create a dictionary in a scratchpad */}} {{ $scratch.SetInMap "message" "english" "Hello World" }} {{ $scratch.SetInMap "message" "french" "Bonjour le monde" }} Dict: {{ $scratch.Get "message" }}

Functions

Boolean Functions 5 < 3 : {{lt 5 3}}
5 > 3 : {{gt 5 3}}
5 ≥ 3 : {{ge 5 3}}
5 ≤ 3 : {{le 5 3}}
5 = 3 : {{eq 5 3}}
5 ≠ 3 : {{ne 5 3}}

Logical Functions true and false : {{and true false}}
true or false : {{or true false}}
not true : {{not true}}

Arithmetic Functions 2 + 3 : {{add 2 3}}
2 - 3 : {{sub 2 3}}
2 x 3 : {{mul 2 3}}
2 ÷ 3 : {{div 2 3}} {{/* Int types */}}
2 ÷ 3 : {{div 2.0 3}} {{/* Float types */}}
2 % 3 : {{mod 2 3}}
2 % 3? : {{modBool 2 3}}

Nested Functions 5/(2 + (3 x 2.0)) : {{div 5 (add 2 (mul 3 2.0))}}

Piped Functions 5/(2 + (3 x 2.0)) : {{mul 3 2.0 | add 2 | div 5}}

Nested + Piped Hybrid 5/(2 + (3 x 2.0)) : {{div 5 (mul 3 2.0 | add 2)}}

Conditionals

If {{$condition := false}} {{/* Condition via if */}} {{if $condition}} {{$condition}} is true. {{else}} {{$condition}} is false. {{end}}

With {{$condition := "test"}}

{{/* Condition via with */}} {{with $condition}} {{.}} is the value of the condition {{else}} Condition is not defined. {{end}}

Cond {{$count := 1}} {{cond (eq $count 1) “page” “pages”}}

Loops

All website pages:
    {{range site.Pages}}
  • {{.Title}}
  • {{end}}
Range context
    {{$title := site.Title}} {{range site.Pages}}
  • {{.Title}} @ {{$title}}
  • {{end}}

Debugging

{{ printf "%#v" site }}