JSON output with and without pagination

I’m trying to render a couple of JSON outputs, given a content folder structure like so:

- content
  - posts
    - 2023
      - post 1
      - post 2
      - post 3
    - 2024
      - post 4
      - post 5
      - post 6

These are the JSON outputs I’m trying to create:

  • posts/index.json, which includes all posts in the posts section, paginated.
  • posts/[year]/calendar.json, which includes all the posts in that year folder, no pagination.

I’ve tried a few different approaches, outlined in the demo repo linked below. None of them get it quite right.

I can work around it by creating a separate content folder with files like years/2023.md and years/2024.md, and then modifying the calendar.json template to retrieve posts from the posts/[year] folders as specified in the front matter. But I would love to find a way to do this without an otherwise unnecessary content section.

Any ideas?

Can both be named index.json? That would make this much simpler.

How many items per pager?

Sure, I’m not married to the naming scheme. It’s just the default for the outputFormat as I have it configured.

Currently I’m doing 25 per page. Presumably this would be easy enough to change.

Instead of coding the JSON by hand, build a data structure then use the jsonify function.

git clone --single-branch -b hugo-forum-topic-52054 https://github.com/jmooring/hugo-testing hugo-forum-topic-52054
cd hugo-forum-topic-52054
hugo server

See layouts/_default/list.json.

3 Likes

This is a really smart solution. Thank you. Your example takes advantage of a few key things I didn’t know about. Namely, the .RegularPagesRecursive and CurrentSection methods, which would have been enough to get me to my goal without anything else.

I’ve adapted your example code to my better fit my dataset. I decided to keep a separate output format for my calendar files, as it makes more sense semantically. But you’re right, it is a bit more work to set it up that way.

I also really appreciate the way you include the pagination data in the JSON output. That’s another whole set of data I didn’t realize was available, which is going to help make my frontend implementation much richer.

I am actually already doing this in my projects; I just didn’t bother with it for my demo repo, as it was a very simple example. But it’s definitely worth it as the data structure gets more complex!

Thanks again for your help.

2 Likes

You’re welcome. I made one change to list.json since my previous post. See line 4.

Change this:

{{- if eq .CurrentSection.Title "Posts" }}

To this:

{{- if eq .CurrentSection .FirstSection }}

That way we’re not hardcoding the section name.

1 Like

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