Mathieu Dhondt
Mathieu Dhondt

Reputation: 8914

Setting a default layout for all Markdown files

I'd like to fetch Markdown files from another repository when building an astro site, but these Markdown files do not have the layout frontmatter property.

Is there a way to 'force' markdown files to use a default layout without touching their frontmatter headers?

Upvotes: 1

Views: 1144

Answers (2)

Tugrul Ates
Tugrul Ates

Reputation: 9687

This is now possible with Content Collections.

Have your Markdown files wrapped in a collection, and have the corresponding [...slug].astro file use the default layout.

---
import { getCollection } from "astro:content";
import DefaultLayout from "../layouts/DefaultLayout.astro";

export async function getStaticPaths() {
  const entries = await getCollection("markdown");
  return entries.map((entry) => ({
    params: { slug: entry.slug },
    props: { entry },
  }));
}

const { entry } = Astro.props;
const { Content } = await entry.render();
---

<DefaultLayout frontmatter={entry.data}>
  <Content />
</DefaultLayout>

Upvotes: 1

Adam Shand
Adam Shand

Reputation: 222

There has been a plugin recently created to do this:

https://github.com/EccentricVamp/astro-default-layout

Plugin is based on these comments if you prefer to roll your own:

https://github.com/withastro/astro/issues/397#issuecomment-1264718819

Upvotes: 3

Related Questions