How to combine .ByParam with Substr and Int?

All my content pages have a unique ID that consists of one letter and a number, e.g. D4. Ordering the pages using .ByParam (combined with .Reverse) works as expected:

  • A4
  • B5
  • C2

Now, if an ID has got a number with more than one digit, this obviously messes up the ordering, since the number is not treated as one integer, but instead as two individual characters (which is completely expected).

  • A1
  • A10
  • A11
  • A2
  • A3

I already came across the substr and int functions: {{ int (substr 1) }} would return the number as an integer that Hugo could work with for ordering.

But how do I properly combine it with .ByParam?

Also, note that I still want the leading character to be considered as the “most significant bit”.

My idea was to use something like this:

{{ with (where (.Site.RegularPages.ByParam "id") "Section" "example") }}
	{{ range sort . (int (substr 1)) }}
		{{ .Render "example" }}
	{{ end }}

But this unfortunately returns: can't evaluate field Params in type page.Pages.

Thank you!

I mean, I could theoretically add the index number as a seperate page parameter, but that would mean certain (and kinda huge) additional efforts in other parts of the website. I’d like to avoid that – but if it’s the only option, I’d go for it. Though, I’d still need some advice on how to proceed then.

Why not pad with leading zero(s)?


1 Like

Good idea, but the ID is presented to the user and must therefore look “pretty”. :grimacing: However, it wouldn’t be too difficult to add a second, seperate ID which would only be used internally for that specific purpose.

(I’ll proceed with this work-around once I’m back at “work” tomorrow.)

Then strip the padding zeros from the displayed value.

I’m using a JS script to generate the front matter for each page, so this is my solution for now:

var orderID = id.substr(0,1) + id.slice(1).padStart(4, '0');

{{ range (where (.Site.RegularPages.ByParam "orderID") "Section" "example") }}
	{{ .Render "example" }}
{{ end }}

Thanks for your advice!

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