Background
In Customized Archetype for This Site, I was using
{{ slicestr .Name 11 | humanize | title }}
in the title
attribute in my site’s archetypes/default.md
, so that the first
11 characters (YYYY-MM-DD-
) would be taken out if I type this command.
$ hugo new post/$(date -I)-<MY_POST_TITLE>.md
In practice, <MY_POST_TITLE>
can be replaced to any title, like
my-post-title
.
Problem
I wanted to create my IntelliJ cheatsheet, so I typed this command.
$ hugo new page/intellij.md
The system returned the following error.
Error: failed to execute archetype template: template: archetype.md:2:11: execut
ing "archetype.md" at <slicestr .Name 11>: error calling slicestr: slice bounds
out of range: template: archetype.md:2:11: executing "archetype.md" at <slicest
r .Name 11>: error calling slicestr: slice bounds out of range
Analysis
The desired page name is IntelliJ
, while the unprocessed .Name
would be
intellij
, which contains only eight characters. Cutting off the first
11 characters leads to “slice bounds out of range” error.
There’re two possible ways to solve the problem:
- use a custom archetype
archetypes/post.md
. - introduce a regular expression replace
replaceRE
.
Solution
I copied the regular expression from the linked discussion in my previous linked post, but it wasn’t working.
{{ .Name | replaceRE "^([0-9_]{11})([a-zA-Z_])" "$2" | replaceRE "_" " " | title }}
To breaking down the problem, I took away the second replaceRE
, "$2"
and all
pipes, so that the replacement looks more similar to the one provided in Hugo’s
official docs for replaceRE
.
{{ replaceRE "^[0-9_]{11}" "" .Name }}
However, the above line returned a string like 2023-04-11-testing-title
. It
took me a while to realize what’s wrong through {{ .Name }}
: the author of the
linked forum named his/her posts like 2023_04_11_foo_bar.md
, but I have been
using hypens -
instead of underscores _
for my file names. It’s because
Google doesn’t like links with underscores _
: links are usually
underlined in normal and/or hovered states.
Finally I replaced the underscore _
with hyphen -
in the above code block,
so that it matches my personal naming convention. My new default Go-HTML
template is now like this.
---
title: "{{ replaceRE `^([0-9-]{11})` "" .Name | humanize | title }}"
date: {{ .Date }}
categories:
- uncategorised
tags:
- notag
draft: true
---