#[Markdoc] Modify frontmatter inside document's transform function

5 messages · Page 1 of 1 (latest)

viscid steeple
#

According to the markdoc docs (https://markdoc.dev/docs/nodes#built-in-nodes), the node type document should store the frontmatter in an attribute called frontmatter (as shown in the sandbox https://markdoc.dev/sandbox?mode=ast)

However, I can't access it from the transform function:

nodes: {
    document: {
        render: null,
        attributes: {
            frontmatter: { type: String },
        },
        transform(node: Node, config: Config): RenderableTreeNode | RenderableTreeNode[] | null {
            const children = node.transformChildren(config);
            const attributes = node.transformAttributes(config);

            console.log(node.attributes) // Prints empty object
            console.log(attributes) // Prints empty object
            console.log(config.variables?.entry.data) // Prints the frontmatter

            return children
        }
    }
}

I have also tried to change the type of the attribute to Object, but no change. And if I add required: true I get a missing attribute error (failed to validate: attribute-missing-required).

I'm aware that I don't need to do that in the transform function (i.e. I can do it by parsing with Markdoc.parse(entry.body) the same way one would extract the headings)

Is it possible to modify the frontmatter in the transform function in a similar way one would use a remark plugin to do so?

abstract lanceBOT
#
Still waiting for an answer?

It looks like no-one has responded to your question yet. People might not be available right now or don’t know how to answer your question. Want an answer while you wait? Try asking our experimental bot in #1095492539085230272.

candid briar
#

He luliic2! Since Markdoc is built on content collections, we avoid passing a "raw" frontmatter object (aka unparsed by your content schema) to Markdoc. We hadn't realized frontmatter was a property supplied by document in Markdoc though, since it appears to be an optional property elsewhere in the documentation

viscid steeple
#

Hi!

It's less about modifying the frontmatter and more about adding to it, similar to remarkPluginFrontmatter (https://docs.astro.build/en/guides/content-collections/#modifying-frontmatter-with-remark)

For example, I use the document's transform method to wrap h2s and it's subsequent tags in <section>s. And while I'm already iterating over the AST I want to calculate the reading time, however I can't pass that information (apart from embedding it directly into the AST). I'm left forced to parse it again after Astro via Markdoc.parse, at which point I might as well embed the html directly instead of calling entry.render

Astro Documentation

Content collections help organize your Markdown and type-check your frontmatter with schemas.