Skip to content

Using a common Layout component for Markdown pages and content collections #8934

@rgov

Description

@rgov

📚 Subject area/topic

Layouts

📋 Page(s) affected (or suggested, for new content)

https://docs.astro.build/en/basics/layouts/#using-one-layout-for-md-mdx-and-astro

📋 Description of content that is out-of-date or incorrect

I can't decide if this is a proposal, a bug report against Astro, or a documentation issue. It boils down to an ugliness with trying to re-use a Layout component between a Markdown page and a Markdown content collection entry, and how frontmatter keys are passed to the Layout component.

The Layout component of a Markdown page accesses frontmatter like Astro.props.frontmatter.author (docs).

The .astro file that renders a Markdown content entry accesses the frontmatter via Astro.props.data (docs). Following the documented conventions, these are passed through to a Layout component, which can then access the frontmatter like Astro.props.author.

This leads to confusion using the same Layout for both content entries and Markdown pages, how should the frontmatter be accessed? This is partially covered in the documentation, giving a workaround like this:

const { author } = Astro.props.frontmatter || Astro.props;

However, this is an incomplete solution, because content collections have a Zod schema that can include field transformations. For example, "dates written without quotes around them are interpreted as Date objects", and arbitrary transformations can be applied with .transform(). These transformations are skipped entirely for Markdown pages.

I think a more complete version would be:

import { collections } from '../content/config';
const { author } = Astro.props.frontmatter ? collections.blog.schema.parse(Astro.props.frontmatter) : Astro.props;

However, I think it would be conceptually clearer to address this another way. It's odd for a Layout component to have to invoke a parser / validator on its props.

🖥️ Reproduction in StackBlitz (if reporting incorrect content or code samples)

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    improve or update documentationEnhance / update existing documentation (e.g. add example, improve description, update for changes)

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions