Amit Jotwani

Amit Jotwani

Setting up default hugo frontmatter

Tinkering
Setting up default hugo frontmatter

I’ve been using Hugo for my personal website, ajot.me, since migrating from Ghost, and I’ve really liked it thus far.

One feature I particularly appreciate about Hugo is its ability to include custom fields in the frontmatter of each post. Beyond standard fields like title and date, you can also incorporate custom fields in each post’s frontmatter and implement conditionals in templates based on these custom field values.

Over time, I’ve introduced several of my own: ogImage for a default image, hideDate to optionally hide dates on certain pages, and canonicalURL for enhanced SEO.

This setup works quite well, but there’s a small hiccup. When I use the hugo new command to draft a post, these custom fields don’t automatically appear. This means I have to add them manually each time.

I wondered if there was a way to simplify this process using a template. As it turns out, Hugo offers a feature called “archetypes” that acts as templates for new posts.

Essentially, Hugo’s archetypes serve as blueprints for your content. They determine the frontmatter that appears by default when you generate new content.

While exploring this, I discovered a key detail about Hugo: it follows a specific sequence when looking for archetypes. For a comprehensive understanding, you can refer to the official Hugo documentation, but in summary, the lookup order is:

  1. archetypes/posts.md
  2. archetypes/default.md
  3. themes/my-theme/archetypes/posts.md
  4. themes/my-theme/archetypes/default.md

Within my Hugo setup, there was already a default.md file in the archetypes directory. So I went ahead and edited it. But for some reason, Hugo seemed to ignore these edits.

So, to make sure my new posts included the desired frontmatter, I created a posts.md file in the same directory. This time, I used the YAML format for the frontmatter. I find it more intuitive than Hugo’s default format.

Inside archetypes/posts.md

---
title: '{{ replace .File.ContentBaseName "-" " " | title }}'
date: {{ .Date }}
draft: true
ogImage: "/img/default-og-image.png"
canonicalURL: 
hideDate: false
description: ""
categories:
  - Developer Experience
  - Journal
  - Thoughts
tags:
  - hugo
  - ghost
---

And that worked. Now, whenever I execute hugo new posts/post_name.md, Hugo crafts a new markdown file for the post, complete with the frontmatter I specified:

---
title: 'Setting up default Hugo frontmatter'
date: 2023-10-30T12:25:52-04:00
draft: true
ogImage: "/img/default-og-image.png"
canonicalURL: 
hideDate: false
description: ""
categories:
  - Tinkering
tags:
  - Hugo
---

If you’re trying to do something similar with Hugo, I hope this helps you out!