Opens an external site in a new window
Mental Health Awareness Month
“Community”
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links
  • Profile
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links

Astro Related Content: using References in Posts & Docs 👨‍👧‍👦 # Astro Related Content: using References in Posts & Docs 👨‍👧‍👦 #

blurry low resolution placeholder image Astro Related Content
  1. Home Rodney Lab Home
  2. Blog Posts Rodney Lab Blog Posts
  3. Astro Astro Blog Posts
<PREVIOUS POST
NEXT POST >
LATEST POST >>

Astro Related Content: using References in Posts & Docs 👨‍👧‍👦 #

Updated 5 months ago
4 minute read
Gunning Fog Index: 0
Content by Rodney
blurry low resolution placeholder image Author Image: Rodney from Rodney Lab
SHARE:

👨‍👧‍👦 Astro Related Content #

If you ever wanted to add links to related blog posts or app features in your Astro blog or documentation site, then Astro related content, which we look at in this video, will set you going on the right track. We are talking about something like the ubiquitous “you liked X, why not try Y” recommendations, on e-commerce and streaming sites. Designing your own site, you might base your related links on SEO priorities, or use AI to generate a content graph. Either way, we see how you can update your Markdown front matter to include the necessary meta and have Astro render the related content links for you.

Although we focus on Markdown content, the technique works almost identically if you are working with Markdoc content source or even a data collection. Hopefully this intro describes what you are looking for. Hit play on the video to see! See the link, further down, for the complete code repo.

You can drop a comment below or reach out for a chat on Element  as well as X @mention  if you have suggestions for improvements or questions.

📹 Video #

Please enable JavaScript to watch the video 📼

Astro Related Content: using References in Posts & Docs

🗳 Poll #

Will you use Markdown or Markdoc to edit content on your next site?
Voting reveals latest results.

🖥 Astro Related Content Example Code #

Markdown Content Front Matter #

src/content/posts/best-medium-format-camera-for-starting-out/
markdown
    
1 ---
2 postTitle: 'Best Medium Format Camera for Starting Out'
3 focusKeyphrase: 'best medium format camera'
4 datePublished: '2022-03-07T16:04:42.000+0100'
5 lastUpdated: '2022-11-12T10:17:52.000+0100'
6 seoMetaDescription: "Best medium format camera for starting out is probably a question at the front of your mind right now! Let's take a look."
7 featuredImage: './best-medium-format-camera-for-starting-out.jpg'
8 placeholder: 'best-medium-format-camera-for-starting-out/
9 draft: false
10 relatedPosts: ['folding-camera', 'twin-lens-reflex-camera']
11 ---

Content Collection Config #

src/content/config.ts
typescript
    
1 import { image_placeholder } from '@rodneylab/picpack';
2 import { defineCollection, reference, z } from 'astro:content';
3 import { readFile } from 'node:fs/promises';
4
5 const postsCollection = defineCollection({
6 type: 'content',
7 schema: ({ image }) =>
8 z.object({
9 postTitle: z.string(),
10 focusKeyphrase: z.string().optional(),
11 datePublished: z.string(),
12 lastUpdated: z.string(),
13 seoMetaDescription: z.string(),
14 featuredImage: image(),
15 featuredImageAlt: z.string(),
16 placeholder: z.string().transform(async (value) => {
17 const { buffer } = await readFile(`./src/content/posts/${value}`);
18 const imageBytes = new Uint8Array(buffer);
19 const { base64 } = image_placeholder(imageBytes);
20 return base64;
21 }),
22 draft: z.boolean(),
23 relatedPosts: z.array(reference('posts')).optional(),
24 }),
25 });
26
27 export const collections = {
28 posts: postsCollection,
29 };

Astro Content Template #

src/pages/pages/[slug].astro
astro
    
1 ---
2 import { Picture } from 'astro:assets';
3 import { getCollection, getEntry } from 'astro:content';
4 import BlogPostSummary from '~components/BlogPostSummary.svelte';
5 import BaseLayout from '~layouts/BaseLayout.astro';
6
7 export async function getStaticPaths() {
8 const posts = await getCollection('posts');
9 return posts.map(
10 ({
11 data: {
12 relatedPosts,
13 //...TRUNCATED
14 },
15 render,
16 slug,
17 }) => {
18 return {
19 params: { slug },
20 props: {
21 relatedPosts,
22 //...TRUNCATED
23 },
24 };
25 },
26 );
27 }
28
29 const { slug } = Astro.params;
30 const {
31 relatedPosts,
32 //...TRUNCATED
33 } = Astro.props;
34
35 const { Content } = await render();
36
37 const relatedPostsArray = relatedPosts
38 ? await Promise.all(
39 relatedPosts?.map(async ({ collection }) => {
40 const {
41 data: { datePublished, postTitle, seoMetaDescription },
42 } = await getEntry(collection, slug);
43
44 return { datePublished, postTitle, seoMetaDescription };
45 }),
46 )
47 : [];
48
49 const { format, width, height } = featuredImage;
50 ---
51
52 <BaseLayout {...seoProps}>
53 <h1>{title}</h1>
54 <div class="image-wrapper">
55 <img class="placeholder" aria-hidden="true" src={placeholder} width={width} height={height} />
56 <Picture
57 pictureAttributes={{ class: 'image lazy' }}
58 src={featuredImage}
59 alt={featuredImageAlt}
60 densities={[1.5, 2]}
61 formats={['avif', 'webp']}
62 fallbackFormat={format}
63 loading="eager"
64 fetchpriority="high"
65 />
66 </div>
67
68 <div class="container">
69 {
70 relatedPosts?.length ? (
71 <aside class="related-posts">
72 <>
73 <h2>You might like to read one of these posts next:</h2>
74 {relatedPostsArray.map(({ datePublished, postTitle, seoMetaDescription }, index) => (
75 <article aria-posinset={index + 1} aria-setsize={relatedPosts.length}>
76 <BlogPostSummary {datePublished} {postTitle} {seoMetaDescription} {slug} />
77 </article>
78 ))}
79 </>
80 </aside>
81 ) : null
82 }
83 <Content />
84 </div>
85 </BaseLayout>

The full demo code is in the Rodney Lab GitHub repo .

🔗 Links #

  • Astro Picture Component
  • Astro Markdoc
  • Astro Markdown Blog Starter
  • Zod docs 
  • Element chat: #rodney matrix chat 
  • Twitter handle: @askRodney 

🙏🏽 Feedback #

Have you found the post useful? Would you prefer to see posts on another topic instead? Get in touch with ideas for new posts. Also, if you like my writing style, get in touch if I can write some posts for your company site on a consultancy basis. Read on to find ways to get in touch, further below. If you want to support posts similar to this one and can spare a few dollars, euros or pounds, please consider supporting me through Buy me a Coffee.

blurry low resolution placeholder image ask Rodney X (formerly Twitter) avatar

Rodney

@askRodney

Just dropped a new video on how you can use 🚀 Astro Content Collections and References to add a “Related Posts” widget to your content site.

Hope you find it useful!

#askRodneyhttps://t.co/r0LCUXWac1

— Rodney (@askRodney) November 10, 2023

Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on X, @[email protected]  on Mastodon and also the #rodney  Element Matrix room. Also, see further ways to get in touch with Rodney Lab. I post regularly on Astro as well as SEO. Also, subscribe to the newsletter to keep up-to-date with our latest projects.

Thanks for reading this post. I hope you found it valuable. Please get in touch with your feedback and suggestions for posts you would like to see. Read more about me …

blurry low resolution placeholder image Rodney from Rodney Lab
TAGS:
ASTRO

Related Posts

blurry low resolution placeholder image Astro Markdoc: Readable, Declarative MDX Alternative 📚

Astro Markdoc: Readable, Declarative MDX Alternative 📚

astro
<PREVIOUS POST
NEXT POST >
LATEST POST >>

Leave a comment …

Your information will be handled in line with our Privacy Policy .

Ask for more

1 Nov 2022 — Astro Server-Side Rendering: Edge Search Site
3 Oct 2022 — Svelte eCommerce Site: SvelteKit Snipcart Storefront
1 Sept 2022 — Get Started with SvelteKit Headless WordPress

Copyright © 2020 – 2025 Rodney Johnson. All Rights Reserved. Please read important copyright and intellectual property information.

  • Home
  • Profile
  • Plus +
  • Newsletter
  • Contact
  • Links
  • Terms of Use
  • Privacy Policy
We use cookies  to enhance visitors’ experience. Please click the “Options” button to make your choice.  Learn more here.