How toAdd custom attributes to Markdoc code fences

If you already customized your Markdoc's Fence component, you can extend it to add custom attributes to it and show them to the user.

Let's see an example adding an optional path of the code. Let's go back to your app/components/fence.tsx component and extend it to accept the path as prop and customize the fence object.

app/components/fence.tsx
type FenceProps = { children: string; language: string; + path?: string; }; -export function Fence({ children, language }: FenceProps) { +export function Fence({ children, language, path }: FenceProps) { let content = Prism.highlight(children, Prism.languages[language], language); return ( - <pre - className={`language-${language}`} - dangerouslySetInnerHTML={{ __html: content }} - /> + <pre className={`language-${language}`} + {path && ( + <header className="flex items-center gap-1 pb-1.5"> + <span className="text-xs leading-none">{path}</span> + </header> + )} + <code dangerouslySetInnerHTML={{ __html: content }} /> + </pre> ); } export const fence = { render: "Fence", - attributes: { language: { type: String } }, + attributes: { language: { type: String }, path: { type: String } }, };

The final code should look like this:

app/components/fence.tsx
type FenceProps = { children: string; language: string; path?: string }; export function Fence({ children, language, path }: FenceProps) { let content = Prism.highlight(children, Prism.languages[language], language); return ( <pre className={`language-${language}`}> {path && ( <header className="flex items-center gap-1 pb-1.5"> <span className="text-xs leading-none">{path}</span> </header> )} <code dangerouslySetInnerHTML={{ __html: content }} /> </pre> ); } export const fence = { render: "Fence", attributes: { language: { type: String }, path: { type: String } }, };

And with this, you can now add the path to the block of code in a Markdown content like this:

```ts {\% path="write the path here" %}
// example code
```

Note: Remove the \ before %, that's there to scape the path for my own code