I decided to move away from using a Jekyll Blog and use Hugo to manage my site and blog posts because I found liquid/ Jekyll too hard to understand what variable are available on my scope along with some other issues so here I like to provide you with what I’ve learned using Hugo’s syntax.
Reading docs can be a pretty dry read and I find it always better to see it in practice so this can be used as a reference sheet to help you out with your Hugo development.
Working with Variables
In your config.toml you’ll see variable declared using brackets “[]” these you can get at in your view by using the “.” syntax.
For Example lets say I have the following in my config.toml
[params]
foo= "bar"
You can get at that in your view by using the following syntax:
syntax used>> {{ .Site.Params.foo }}
output in view>> bar
Declaring variables in the view
This the the javascript equivalent of declaring variable in Hugo In Javascript
var paginator = foo
in hugo view
{{ $paginator := foo}}
Getting at variables in the data/ folder
Using the {{ .Site.Data }}
syntax gets all the .toml files inside the data/ folder
So lets say I have the following in my data folder
data/
work.toml
blog.toml
Inside my work.toml
file
title = "Work"
```bash
[[projects]]
name = "cera.io"
folder = 'proj-1'
file= 'work/proj-1.html'
[[projects]]
name = "everythingrideshare.io"
folder = 'proj-3'
file= 'work/proj-3.html'
And using {{ .Site.Data }}
will display the following in the view (I beautified the results
so its easier to read)
map[
work:map[title:Work
projects: [map[name:Cera.io folder:proj-1 file:work/proj-1.html]
map[name:Everythingrideshare.io folder:proj-3 file:work/proj-3.html]
]
blog:map[title:blog]
]
where using >>
{{ .Site.Data.blog }}
outputs >>
map[title:blog]
but to be safe use
could crash >> {{ .Site.Data.blog }}
instead use (the safe way to display it) >> {{ with .Site.Data.blog }}{{ . }}{{ end }}
Loops
to loop through each item in blog.toml
(with only one item of “title”)
range loop >>
{{ range .Site.Data.blog }}<br />{{ . }}{{ end }}
outputs >>
Blog
to loop though each projects name in work.toml
range loop >>
```bash {{ range .Site.Data.work.projects }}
- {{ .name }}{{ end }}
outputs:
```bash
- cera.io
- everythingrideshare.io
You can also display key and values (name $key and $value what ever you want. The “$” isn’t required its just used as a way let you know its a variable you declared)
range loop (with declared $key and $value vars):
{{ range $key,$value := .Site.Data.work.projects }}
{{$key}} - {{$value}}
{{end}}
outputs:
name - cera.io
name - everythingrideshare.io
Hope This helps get you started!