How can I render images from markdown to HTML in Astro using @astropub/md?

38 Views Asked by At

I'm working on a blog in Astro, and I'm trying to render the markdown from the blog post to HTML in using @astropub/md?

Sample markdown blog post

---
title: Sample image
meta:
  description: This is a simple post to say hello to the world.
pubDate: 2024-03-28
---

![an image](./images/mountain.jpeg)

Blog overview Astro template

---
import { getCollection } from "astro:content";
import { Markdown } from "@astropub/md";


const allPosts = await getCollection("posts");
---

<ul>
  {
    allPosts.map((post: any) => (
      <li>
        <a href={`/blog/${post.slug}/`}>{post.data.title}</a>

        <Markdown of={post.body} />
      </li>
    ))
  }
</ul>

The issue

The image is only loading on the single blog post, not in the blog overview. It's almost as if Vite isn't parsing images loaded through @astropub/md's component.

Blog overview (doesn't load):

The src of the img tag is: ./images/mountain.jpeg

screenshot

Blog post (works fine):

The src of the img tag is: /_image?href=...

screenshot

1

There are 1 best solutions below

2
Bryce Russell On

Instead of using @astropub/md, you can use the Content Collections API to render your content. For example:

---
import { getCollection } from "astro:content";

const allPosts = await getCollection("posts");
---

<ul>
  {
    allPosts.map(async (post) => {
      const { Content } = await post.render()

      return (
        <li>
          <a href={`/blog/${post.slug}/`}>{post.data.title}</a>
          <Content />
        </li>
      )
    })
  }
</ul>