Skip to content

Instantly share code, notes, and snippets.

@hdevilbiss
Last active December 17, 2020 06:27
Show Gist options
  • Save hdevilbiss/55c80e985e5850e5705489b6051b9165 to your computer and use it in GitHub Desktop.
Save hdevilbiss/55c80e985e5850e5705489b6051b9165 to your computer and use it in GitHub Desktop.
Hugo front matter: Loop through all categories from the front matter of a given piece of content

Looping through Hugo front matter categories

Each piece of content in Hugo should have front matter. Front matter is like post meta. It can be formatted 4 ways: JSON, YAML, TOML, or ORG.

yaml format

---
title: "{{ replace .Name "-" " " | title }}"
date: {{ .Date }}
draft: true
categories = ["Hugo","Front Matter","Templating"]
---

You might want to loop through all the strings in a given post's categories array. How is this done?

Using the range function

The Hugo range function is an iterator function, useful for templating.

Each category in the Categories array can be referred to with the $category variable.

{{ range $category := .Params.Categories }}
  <p>
    {{ $category }}
  </p>
{{ end }}

The .Params variable refers to the page-level parameters.

Page-level .Params [such as tags and categories] are only accessible in lowercase.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment