Search code examples
astrojs

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?


Solution

  • 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>