Merge local and data-driven content in list

#1

I’m playing around with data-driven content, using getJSON to retrieve a list of bookmarks from Pinboard and a list of posts from Micro.blog.

I’d like to build a front-page that lists everything, including local blog posts, sorted by date. Pagination isn’t important, let’s say it lists the latest 20 items. I’m familiar with the union function, but I can’t get it to work with the results from getJSON.

Is my goal possible, and if so: any tips for how to pull it off?

#2

Can you share the code you’ve attempted this with so far?

#3

Kind of, I set up a demo repository for you.

The main idea is I have two inputs:

{{ $localPosts := ($.Site.GetPage "section" "blog").Pages }}
{{ $microPosts := getJSON "https://micro.blog/posts/discover" }}

Is there a way to make them… I don’t know, “compatible” with each other? My goal here is to combine $localPosts and $microPosts into one set to range through and sort by date. In the above case the dates are accessible by .Date and .date_published – how would I combine and sort this?

#4

You could do a ‘manual’ union and cast each to the same ‘type’ as you go:

{{ $combi := slice }}

{{ $localPosts := ($.Site.GetPage "section" "blog").Pages }}
{{ $microPosts := getJSON "https://micro.blog/posts/discover" }}

{{- range $localPosts -}}
{{ $combi = $combi | append (dict "url" .Permalink "date_published" .Date "content_html" .Content) }}
{{- end -}}

{{- range $microPosts.items -}}
{{ $d := .date_published | time }}
{{ $combi = $combi | append (dict "url" .url "date_published" $d "content_html" .content_html) }}
{{- end -}}

{{ range sort $combi "date_published" "asc" }}
{{ . }}
{{ end }}
5 Likes
Cross-index data from multiple files
#5

So that’s how you do it! :slight_smile: I was hoping it would be something like that, but didn’t know about slice. Thank you very much for the solution!

#6

I’m following most of what’s happening here, however I’m unsure about what the pipe character (|) is doing on lines 7, 11, and 12? Is that basically saying “and also do this”?

#7

Kinda. It means to pipe the output of one action and use it as the input for another action.

Checkout the docs for more details: https://gohugo.io/templates/introduction/#pipes

1 Like