Render your Astro markdown content for your overviews

post

I wanted to create a roll-up of the latest news articles on our new BIWUG community site (which still needs to be released).

Show image BIWUG News Rollup
BIWUG News Rollup

When I retrieved the news collection data, I only got the front matter data and the markdown content.

Looking at the Astro documentation, I found several ways to get the HTML. The first one was to use the marked dependency, although I found an easier and better way to utilize the Astro.glob() functionality.

The Astro.glob() function is a way to retrieve files from a directory. It takes a glob pattern as its input, and it returns an array of the files that match the pattern.

For example, the following code would retrieve all of the news articles in the content/news directory:

1
const allNewsPosts = await Astro.glob(../content/news/*.md);

The nice part about the Astro.glob() function is that it returns the front matter data and the Astro Content component. This means that you can use the Astro Content component to render the HTML.

On the BIWUG website, I used it as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
---
const allNewsPosts = await Astro.glob(`../content/news/*.md`)
const newsPosts = allNewsPosts.map(n => ({
  title: n.frontmatter.title,
  Content: n.Content
}));
---

<section class="news__section mt-16">
  <h2>Stay Up to Date</h2>
  <h3>Latest News and Exciting Events</h3>

  <div class="mx-auto mt-8 grid max-w-max grid-cols-1 place-content-center gap-x-16 gap-y-12 md:grid-cols-2">
    {
      newsPosts.map(({ title, Content }) => (
        <article class="bg-white space-y-4 p-8 shadow-md rounded-md border border-gray-200">
          <h2>{title}</h2>

          <Content />
        </article>
      ))
    }
  </ul>
</section>
info

You can also use the getCollection() API, but this requires you to use entry.render() for each news article.

Comments

Back to top