1

I want to render the contents of multiple .md files on a single page using Astro.

I have this file structure:

pages/
  items/
    item-1.md
    item-2.md
    item-3.md
    // etc
  index.astro

item-1.md looks like this:

---
title = 'Item 1'
---

Item 1 main text

And in index.astro:

---
const items = await Astro.glob([
    './items/*.md',
]);
---

<html lang="en">
    <body>
        {items.map((item) =>
            item.Content
        )}
    </body>
</html>

What I get as a result is:

[object Object][object Object][object Object]

Instead of the expected:

Item 1 main text
Item 2 main text
Item 3 main text

How can I make it so that the output HTML calculated from Markdown appears on the page?

Santa
  • 43
  • 4

1 Answers1

4

item.Content is an Astro component, so in your index.astro file you will need to render it like this:

---
const items = await Astro.glob('./items/*.md');
---

<html lang="en">
    <body>
        {items.map((item) =>
            <item.Content />
        )}
    </body>
</html>

You could also destructure it in the map, but these are functionally equivalent:

        {items.map(({ Content }) =>
            <Content />
        )}
swithinbank
  • 1,127
  • 1
  • 6
  • 15
  • 1
    How do you can excerpt from the content rather than the whole thing? – toxaq Mar 04 '23 at 05:05
  • 1
    @toxaq To do that, you’ll need to decide how the excerpt is generated. If you want to slice the first n characters, or first n paragraphs, you’ll need to grab the raw Markdown, chop it up based on that logic and then potentially either strip Markdown characters, or use a custom Markdown renderer to render it to HTML. It depends a lot on your use case, so I’d recommend asking a new SO question where you can provide details about your project and what you’re trying to do. – swithinbank Mar 12 '23 at 21:40
  • 1
    Hey @swithinbank, thanks for that. Worked it out in the end. The confusion arose because I was using the content collection which only returns a component, not the rendered text. There's a lot more raw stuff available with the glob method so basically had to double load the files in the end to not have to rewrite the whole blog from scratch. – toxaq Mar 12 '23 at 21:49
  • 1
    Content collections should return a `body` property that is similar to the `rawContent()` you get in the glob version. Glad you’ve got it working! – swithinbank Mar 13 '23 at 22:57