How to get the position of a blog post?

Hi guys,

I would like to add a prefix to every title’s blog post.

For example listed as such on the home page;

1246 Blog post 1246 title
0023 Blog post 23 title

0002 Blog post 3 title
0001 blog post 1 title
0000 blog post 0 title

How do I achieve this? Can you do basic math and logic in Hugo templates to do this?

It also seems to require being able to count the position of published blog posts from the first published to latest. How can I do that?

Thanks in advance.

If you want to change the value returned by {{ .Title }} you need to edit the title field in front matter. Pages do not have permanent record or node IDs as you might find with something like WordPress or Drupal.

If you want to prefix the title with a counter when listing pages (and I have no idea why you would want to to do this), do either of these:

{{/* Ascending counter ( 0 through N-1) */}}
{{ $c := 0 }}
{{ range where site.RegularPages "Section" "posts" }}
  {{ $t := printf "%04d %s" $c .Title }}
  <h2><a href="{{ .RelPermalink }}">{{ $t }}</a></h2>
  {{ $c = add $c 1 }}
{{ end }}

{{/* Descending counter (N-1 through 0) */}}
{{ $c := sub (len $p) 1 }}
{{ range where site.RegularPages "Section" "posts" }}
  {{ $t := printf "%04d %s" $c .Title }}
  <h2><a href="{{ .RelPermalink }}">{{ $t }}</a></h2>
  {{ $c = sub $c 1 }}
{{ end }}
1 Like

Thank you very much! I got it working exactly the way I wanted. Final results are here https://asindu.xyz/

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.