### Start Project Source: https://github.com/markdoc/docs/blob/main/pages/docs/examples/html.md Run this command to start the project. ```shell npm run start ``` -------------------------------- ### Install Dependencies Source: https://github.com/markdoc/docs/blob/main/examples/simple-nextjs/README.md Run this command to install the necessary packages for the project. Use npm or yarn. ```bash npm install # or yarn install ``` -------------------------------- ### Install Markdoc with yarn Source: https://github.com/markdoc/docs/blob/main/pages/docs/getting-started.md Use yarn to install the Markdoc library in your project. ```shell yarn add @markdoc/markdoc ``` -------------------------------- ### Install Markdoc Core Library Source: https://context7.com/markdoc/docs/llms.txt Install the Markdoc core library using npm or yarn. ```shell npm install @markdoc/markdoc # or yarn add @markdoc/markdoc ``` -------------------------------- ### Install Markdoc with npm Source: https://github.com/markdoc/docs/blob/main/pages/docs/getting-started.md Use npm to install the Markdoc library in your project. ```shell npm install @markdoc/markdoc ``` -------------------------------- ### Install Markdoc Next.js Package Source: https://github.com/markdoc/docs/blob/main/pages/docs/nextjs.md Install the necessary packages for integrating Markdoc with Next.js. ```shell npm install @markdoc/next.js @markdoc/markdoc ``` -------------------------------- ### Start Markdoc Development Server Source: https://github.com/markdoc/docs/blob/main/README.md Execute this command to start the development server for Markdoc. Access the site at http://localhost:3000. ```bash npm run dev ``` -------------------------------- ### Install Markdoc Dependencies Source: https://github.com/markdoc/docs/blob/main/README.md Run this command in your local environment after forking and cloning the repository to install project dependencies. ```bash npm install ``` -------------------------------- ### Full Markdoc Configuration Example Source: https://github.com/markdoc/docs/blob/main/pages/docs/config.md A comprehensive example demonstrating how to configure custom nodes, tags, variables, functions, and partials within a single Markdoc configuration object. ```javascript /** @type {import('@markdoc/markdoc').Config} */ const config = { nodes: { heading: { render: 'Heading', attributes: { id: { type: String }, level: { type: Number } } } }, tags: { callout: { render: 'Callout', attributes: { title: { type: String } } } }, variables: { name: 'Dr. Mark', frontmatter: { title: 'Configuration options' } }, functions: { includes: { transform(parameters, config) { const [array, value] = Object.values(parameters); return Array.isArray(array) ? array.includes(value) : false; } } }, partials: { 'header.md': Markdoc.parse(`# My header`) } }; const content = Markdoc.transform(ast, config); ``` -------------------------------- ### Run Development Server Source: https://github.com/markdoc/docs/blob/main/examples/simple-nextjs/README.md Start the local development server to preview your documentation site. Use npm or yarn. ```bash npm run dev # or yarn dev ``` -------------------------------- ### Example Rendered HTML Output Source: https://github.com/markdoc/docs/blob/main/pages/docs/render.md This is an example of the HTML output generated by rendering Markdoc content. ```html

Getting started

Run this command to install the Markdoc library:

``` -------------------------------- ### Markdoc Content Example Source: https://context7.com/markdoc/docs/llms.txt Example of a Markdoc file demonstrating the use of frontmatter, custom tags like 'callout', and links. ```markdown --- title: Getting Started description: Install and use Markdoc --- # {% $markdoc.frontmatter.title %} {% callout type="note" %} Run `npm install @markdoc/markdoc` to get started. {% /callout %} {% link href="/docs/syntax" %}Learn the syntax{% /link %} ``` -------------------------------- ### Example HTML Output Source: https://github.com/markdoc/docs/blob/main/pages/docs/render.md An example of the HTML output generated by Markdoc's HTML renderer. ```html

Getting started

Run this command to install the Markdoc library:

``` -------------------------------- ### Project Structure with Markdoc Schema Source: https://github.com/markdoc/docs/blob/main/pages/docs/nextjs.md Example project structure showing the location of the Markdoc schema directory. ```directory . ├── components │ ├── ... │ └── Link.js ├── markdoc │ ├── functions.js │ ├── nodes │ │ ├── ... │ │ ├── link.markdoc.js │ │ └── index.js │ └── tags │ ├── ... │ └── index.js ├── pages │ ├── _app.js │ └── index.md └── next.config.js ``` -------------------------------- ### JSON Frontmatter Example Source: https://github.com/markdoc/docs/blob/main/pages/docs/frontmatter.md Example of frontmatter structured using JSON syntax. This is a common choice for data interchange. ```json --- { "title": "Authoring in Markdown", "description": "Quickly author amazing content with Markdoc syntax, a superset of Markdown.", "date": "2022-04-01" } --- ``` -------------------------------- ### GraphQL Frontmatter Example Source: https://github.com/markdoc/docs/blob/main/pages/docs/frontmatter.md Example of frontmatter structured using GraphQL syntax. This can be useful if your content is managed via a GraphQL API. ```graphql --- { page { title description date } } --- ``` -------------------------------- ### Full Attribute Example Source: https://github.com/markdoc/docs/blob/main/spec/index.md Demonstrates the syntax for a full attribute with a string and an array value. ```markdoc {% foo="bar" baz=[1, 2, 3] %} ``` -------------------------------- ### YAML Frontmatter Example Source: https://github.com/markdoc/docs/blob/main/pages/docs/frontmatter.md Example of frontmatter structured using YAML syntax. This is commonly used for page-level metadata. ```yaml --- title: Authoring in Markdoc description: Quickly author amazing content with Markdoc syntax, a superset of Markdown. date: 2022-04-01 --- ``` -------------------------------- ### Example Markdoc File Structure Source: https://github.com/markdoc/docs/blob/main/pages/docs/nextjs.md Illustrates where to place your Markdoc files within a Next.js project structure. ```directory pages ├── _app.js ├── docs │   └── getting-started.md └── index.md ``` -------------------------------- ### TOML Frontmatter Example Source: https://github.com/markdoc/docs/blob/main/pages/docs/frontmatter.md Example of frontmatter structured using TOML syntax. This format is another option for page-level metadata. ```toml --- title = "Authoring in Markdoc" description = "Quickly author amazing content with Markdoc syntax, a superset of Markdown." date = "2022-04-01" --- ``` -------------------------------- ### Basic Markdoc Content Source: https://github.com/markdoc/docs/blob/main/pages/docs/nextjs.md Example of a Markdoc file with frontmatter and basic Markdown content. ```markdown --- title: Get started with Markdoc description: How to get started with Markdoc --- # Get started with Markdoc ``` -------------------------------- ### Example JSON Renderable Tree Node Source: https://github.com/markdoc/docs/blob/main/pages/docs/render.md An example structure of a Markdoc renderable tree node, representing content ready for rendering. ```json { "name": "article", "attributes": {}, "children": [ { "name": "h1", "attributes": {}, "children": ["Header"], "$$mdtag": true } ], "$$mdtag": true } ``` -------------------------------- ### Example JSON AST Node Source: https://github.com/markdoc/docs/blob/main/pages/docs/render.md An example structure of a Markdoc Abstract Syntax Tree (AST) node, representing parsed content. ```json { "type": "document", "attributes": {}, "children": [ { "type": "paragraph", "attributes": {}, "children": [...], "lines": [0, 2], "location": { "start": { "line": 0 }, "end": { "line": 2 } }, "errors": [], "inline": false, } ], "lines": [], "errors": [], "inline": false } ``` -------------------------------- ### Assemble Config and Render Markdown with Custom Tags Source: https://context7.com/markdoc/docs/llms.txt Assemble the Markdoc configuration with custom tags and then parse, transform, and render Markdown content that utilizes these custom tags. This example demonstrates rendering a 'callout' and a 'button' tag. ```javascript // Assemble config and render import Markdoc from '@markdoc/markdoc'; import { callout } from './schema/Callout.markdoc'; import { button } from './schema/Button.markdoc'; const config = { tags: { callout, button } }; const doc = ` {% callout type="warning" title="Important" %} Back up your data before proceeding. {% /callout %} {% button href="/docs/next-steps" label="Continue" variant="primary" /%} `; const ast = Markdoc.parse(doc); const content = Markdoc.transform(ast, config); const html = Markdoc.renderers.html(content); ``` -------------------------------- ### Basic AST Validation Example Source: https://github.com/markdoc/docs/blob/main/pages/docs/validation.md Parse a Markdoc document and then validate its AST. The `errors` array will contain any syntax issues found. ```javascript const doc = `# Heading`; const ast = Markdoc.parse(doc); const errors = Markdoc.validate(ast, config); // Do something with the errors ``` -------------------------------- ### Built-in Markdoc Tags Example Source: https://context7.com/markdoc/docs/llms.txt Demonstrates the usage of built-in Markdoc tags for conditionals, rich tables with colspan, and partial content inclusion with scoped variables. ```markdown {% comment %} --- Conditionals --- {% /comment %} {% if and($user.loggedIn, equals($user.plan, "pro")) %} Welcome back, {% $user.name %}! You have **Pro** access. {% else $user.loggedIn /%} Upgrade to Pro to unlock all features. {% else /%} Please log in to continue. {% /if %} {% comment %} --- Rich table with colspan and code --- {% /comment %} {% table %} * Function {% width="30%" %} * Returns {% width="20%" %} * Example {% width="50%" %} --- * `equals` * `boolean` * ``` equals($plan, "pro") => true ``` --- * `default` * `mixed` * `default($name, "Anonymous")` --- * Two columns {% colspan=2 %} * Single remaining cell {% /table %} {% comment %} --- Partials with scoped variables --- {% /comment %} {% partial file="sdk-install.md" variables={sdk: "Python", version: "3.11"} /%} ``` -------------------------------- ### Built-in Markdoc Functions Example Source: https://context7.com/markdoc/docs/llms.txt Illustrates the use of built-in Markdoc functions for strict equality checks, boolean logic (and, or, not), providing default values, and debugging variables. ```markdown {% comment %} equals — strict equality {% /comment %} {% if equals($theme, "dark") %} Dark mode is active. {% /if %} {% comment %} and / or / not — boolean logic {% /comment %} {% if and(not($maintenance), or($user.admin, $user.beta)) %} Feature is accessible. {% /if %} {% comment %} default — fallback for undefined variables {% /comment %} Welcome, {% default($user.displayName, "Guest") %}! {% comment %} debug — inspect variable values during development {% /comment %} {% debug($config) %} ``` -------------------------------- ### Simple JavaScript Variable Declaration Source: https://github.com/markdoc/docs/blob/main/examples/html-nodejs/content/home.md A basic example of declaring a string variable in JavaScript. ```javascript const x = 'test'; ``` -------------------------------- ### Configure Markdoc with Custom Tags Source: https://github.com/markdoc/docs/blob/main/pages/docs/tags.md Pass your custom tag definitions to the Markdoc `config` object. This example shows how to include the 'callout' tag definition. ```javascript import { callout } from './schema/Callout.markdoc'; import * as components from './components'; /** @type {import('@markdoc/markdoc').Config} */ const config = { tags: { callout } }; const doc = ` # My first custom tag `; const ast = Markdoc.parse(doc); const content = Markdoc.transform(ast, config); const children = Markdoc.renderers.react(content, React, { components }); ``` -------------------------------- ### Register Custom Functions in Markdoc Source: https://github.com/markdoc/docs/blob/main/pages/docs/nextjs.md Define custom functions for Markdoc by creating a `/markdoc/functions.js` file. This example shows how to create an `upper` function that converts its first parameter to uppercase. ```javascript // markdoc/functions.js export const upper = { transform(parameters) { const string = parameters[0]; return typeof string === 'string' ? string.toUpperCase() : string; } }; ``` -------------------------------- ### Configure Custom Nodes Source: https://github.com/markdoc/docs/blob/main/pages/docs/nodes.md Pass custom nodes to the `config` object to customize Markdoc's rendering. This example shows how to configure a custom `heading` node. ```javascript import { heading } from './schema/Heading.markdoc'; import * as components from './components'; /** @type {import('@markdoc/markdoc').Config} */ const config = { nodes: { heading } }; const ast = Markdoc.parse(doc); const content = Markdoc.transform(ast, config); const children = Markdoc.renderers.react(content, React, { components }); ``` -------------------------------- ### Prism.js Syntax Highlighting with Custom Fence Node Source: https://github.com/markdoc/docs/blob/main/pages/docs/examples/index.md Integrates Prism.js for syntax highlighting in code blocks by creating a custom 'Fence' node. This example shows how to use the 'react-prism' component and configure Markdoc to use this custom node. ```javascript // [Source example](https://github.com/markdoc/docs/blob/main/components/Code.js) import 'prismjs'; import 'prismjs/themes/prism.css'; import Prism from 'react-prism'; export function Fence({ children, language }) { return ( {children} ); } const fence = { render: 'Fence', attributes: { language: { type: String } } }; const content = Markdoc.transform(ast, { nodes: { fence } }); Markdoc.renderers.react(content, React, { components: { Fence } }); ``` -------------------------------- ### Register and Render Markdown with Custom Heading Node Source: https://context7.com/markdoc/docs/llms.txt Register the custom 'heading' node in the Markdoc configuration and then parse, transform, and render Markdown content. This example shows how a heading with an explicit ID is processed. ```javascript // Register the custom node import Markdoc from '@markdoc/markdoc'; import { heading } from './schema/Heading.markdoc'; const ast = Markdoc.parse(`## Installation {% #installation %}\nRun npm install.`); const content = Markdoc.transform(ast, { nodes: { heading } }); const html = Markdoc.renderers.html(content); //

Installation

Run npm install.

``` -------------------------------- ### Register Built-in Next.js Markdoc Tags Source: https://github.com/markdoc/docs/blob/main/pages/docs/nextjs.md Include built-in Next.js Markdoc tags by exporting them from your schema directory (e.g., `/markdoc/`). This example shows exporting specific tags or all tags from `@markdoc/next.js/tags`. ```javascript // markdoc/tags/Next.markdoc.js export { comment, head, link, script } from '@markdoc/next.js/tags'; // or export * from '@markdoc/next.js/tags'; ``` -------------------------------- ### Build Command Source: https://github.com/markdoc/docs/blob/main/pages/docs/examples/html.md Command to build the project, typically used to compile assets and prepare the application for deployment. ```shell npm run build ``` -------------------------------- ### Interpolating a Variable Source: https://github.com/markdoc/docs/blob/main/spec/index.md Example of inserting a Markdoc variable into the document text. ```markdoc Hello {% $username %} ``` -------------------------------- ### Use Markdoc to parse, transform, and render content Source: https://github.com/markdoc/docs/blob/main/pages/docs/getting-started.md Demonstrates the basic workflow of parsing Markdown-like source, transforming it with configuration, and rendering it to HTML. ```javascript const source = '# Markdoc'; const ast = Markdoc.parse(source); // prettier-ignore const content = Markdoc.transform(ast, /* [config](/docs/config) */); const html = Markdoc.renderers.html(content); ``` -------------------------------- ### Equivalent Full Attributes for Shorthand Source: https://github.com/markdoc/docs/blob/main/spec/index.md Illustrates the equivalent full attribute syntax for the shorthand ID and class attributes. ```markdoc {% id="foo" class="bar" %} ``` -------------------------------- ### Configure Markdoc Mode Source: https://github.com/markdoc/docs/blob/main/pages/docs/nextjs.md Set the `mode` option in `withMarkdoc` to 'static' for pre-rendering pages at build time using `getStaticProps`. ```javascript module.exports = withMarkdoc({ mode: 'static' })({ pageExtensions: // [...](https://nextjs.org/docs/api-reference/next.config.js/custom-page-extensions) }); ``` -------------------------------- ### Table Without Headings Source: https://github.com/markdoc/docs/blob/main/pages/docs/tags.md Example of a Markdoc table structure without explicit headings, using '---' to separate content rows. ```markdown {% table %} --- * foo * bar --- * foo * bar {% /table %} ``` -------------------------------- ### Define Custom Tag: Kebab Case Source: https://github.com/markdoc/docs/blob/main/pages/docs/nextjs.md Example of exporting a default object in `markdoc/tags.js` to define a custom tag with a kebab-case name, 'special-button'. ```javascript // markdoc/tags.js export default { 'special-button': { render: SpecialButton, attributes: { href: { type: String } } } }; ``` -------------------------------- ### Block-level Tag Parsing Source: https://github.com/markdoc/docs/blob/main/public/spec.html A tag is parsed as block-level when its opening and closing markers are on lines by themselves. This example shows 'foo' as a block-level tag containing a paragraph. ```markdoc {% foo %} This is content inside of a block-level tag {% /foo %} ``` -------------------------------- ### Using Variables in Markdoc Source: https://context7.com/markdoc/docs/llms.txt Demonstrates how to use variables within Markdoc documents for dynamic content rendering. Ensure variables are defined in the Markdoc configuration. ```javascript import Markdoc from '@markdoc/markdoc'; const doc = `Hello, {% $user.name %}! You have access to the beta program. {% /if %} {% if equals($user.plan, "enterprise") %} Enterprise support: {% $support.email %} {% /if %} Your SDK version: {% $sdk.version %} `; /** @type {import('@markdoc/markdoc').Config} */ const config = { variables: { flags: { showBeta: true }, user: { name: 'Dr. Mark', plan: 'enterprise' }, support: { email: 'enterprise@example.com' }, sdk: { version: '2.4.1' } } }; const ast = Markdoc.parse(doc); const content = Markdoc.transform(ast, config); const html = Markdoc.renderers.html(content); ``` -------------------------------- ### Configure Next.js with Markdoc Source: https://context7.com/markdoc/docs/llms.txt Configure the next.config.js file to enable Markdoc integration, specifying the schema path and mode. ```javascript // next.config.js const withMarkdoc = require('@markdoc/next.js'); module.exports = withMarkdoc({ mode: 'static', // 'static' | 'server' schemaPath: './markdoc', // where tag/node/function schemas live tokenizerOptions: { allowComments: true } })({ pageExtensions: ['md', 'mdoc', 'js', 'jsx', 'ts', 'tsx'] }); ``` -------------------------------- ### Inline Tags Source: https://github.com/markdoc/docs/blob/main/pages/docs/tags.md Inline tags are automatically wrapped in a paragraph node. This example shows multiple inline highlight tags within a code tag. ```markdown {% code %} {% highlight %}Inline tag 1{% /highlight %} {% highlight %}Inline tag 2{% /highlight %} {% /code %} ``` -------------------------------- ### Configure Variables for Rendering Source: https://github.com/markdoc/docs/blob/main/pages/docs/config.md Define a configuration object to specify variables, such as `$version`, and pass it to the `transform` function. This allows dynamic content injection during rendering. ```javascript /** @type {import('@markdoc/markdoc').Config} */ const config = { variables: { version: "1.0" }}; const ast = Markdoc.parse("This is version {% $version %}"); const content = Markdoc.transform(ast, config); const html = Markdoc.renderers.html(content); ``` -------------------------------- ### Configure Next.js with Markdoc Source: https://github.com/markdoc/docs/blob/main/pages/docs/nextjs.md Update your `next.config.js` to enable Markdoc processing and specify page extensions. ```javascript const withMarkdoc = require('@markdoc/next.js'); module.exports = withMarkdoc(/* [options](#options) */)({ pageExtensions: ['md', 'mdoc', 'js', 'jsx', 'ts', 'tsx'] }); ``` -------------------------------- ### Transform AST to Renderable Tree with Config Source: https://context7.com/markdoc/docs/llms.txt Applies a configuration to an AST to produce a serializable renderable tree. Variables are resolved, and custom tags are processed. This is useful for server-side operations or passing data between client and server. ```javascript import Markdoc from '@markdoc/markdoc'; import yaml from 'js-yaml'; const source = ` --- title: My Page --- # {% $frontmatter.title %} {% if equals($env, "production") %} This only appears in production. {% /if %} {% callout type="warning" title="Heads up" %} Read this carefully. {% /callout %} `; const ast = Markdoc.parse(source); // Parse YAML frontmatter manually const frontmatter = ast.attributes.frontmatter ? yaml.load(ast.attributes.frontmatter) : {}; /** @type {import('@markdoc/markdoc').Config} */ const config = { variables: { frontmatter, env: 'production' }, tags: { callout: { render: 'Callout', attributes: { type: { type: String, matches: ['note', 'warning', 'caution', 'check'] }, title: { type: String } } } } }; const content = Markdoc.transform(ast, config); // Renderable tree shape (abbreviated): // { // name: 'article', // attributes: {}, // children: [ // { name: 'h1', attributes: {}, children: ['My Page'], $$mdtag: true }, // { name: 'Callout', attributes: { type: 'warning', title: 'Heads up' }, ... } // ], // $$mdtag: true // } ``` -------------------------------- ### Creating a Custom DateTime Attribute Type Source: https://github.com/markdoc/docs/blob/main/pages/docs/attributes.md Implement a custom attribute type by creating a class with `validate` and `transform` methods. This example creates a `DateTime` attribute. ```javascript export class DateTime { validate(value, config) { if (typeof value !== 'string' || isNaN(Date.parse(value))) return [ { id: 'invalid-datetime-type', level: 'critical', message: 'Must be a string with a valid date format' } ]; return []; } transform(value, config) { return Date.parse(value); } } ``` -------------------------------- ### Markdoc.transform(ast, config?) Source: https://context7.com/markdoc/docs/llms.txt Takes the AST produced by `parse` and applies the config (tags, nodes, variables, functions) to produce a serializable renderable tree. Variables are resolved to static scalar values at this stage. ```APIDOC ## Markdoc.transform(ast, config?) — Transform AST into a renderable tree Takes the AST produced by `parse` and applies the config (tags, nodes, variables, functions) to produce a serializable renderable tree. Variables are resolved to static scalar values at this stage. The renderable tree can be passed over the wire or used for server-side operations like building a table of contents. ```js import Markdoc from '@markdoc/markdoc'; import yaml from 'js-yaml'; const source = ` --- title: My Page --- # {% $frontmatter.title %} {% if equals($env, "production") %} This only appears in production. {% /if %} {% callout type="warning" title="Heads up" %} Read this carefully. {% /callout %} `; const ast = Markdoc.parse(source); // Parse YAML frontmatter manually const frontmatter = ast.attributes.frontmatter ? yaml.load(ast.attributes.frontmatter) : {}; /** @type {import('@markdoc/markdoc').Config} */ const config = { variables: { frontmatter, env: 'production' }, tags: { callout: { render: 'Callout', attributes: { type: { type: String, matches: ['note', 'warning', 'caution', 'check'] }, title: { type: String } } } } }; const content = Markdoc.transform(ast, config); // Renderable tree shape (abbreviated): // { // name: 'article', // attributes: {}, // children: [ // { name: 'h1', attributes: {}, children: ['My Page'], $$mdtag: true }, // { name: 'Callout', attributes: { type: 'warning', title: 'Heads up' }, ... } // ], // $$mdtag: true // } ``` ``` -------------------------------- ### Import Markdoc with CommonJS Source: https://github.com/markdoc/docs/blob/main/pages/docs/getting-started.md Import the Markdoc library using CommonJS syntax. ```javascript const Markdoc = require('@markdoc/markdoc'); ``` -------------------------------- ### Access Frontmatter in Markdoc Content Source: https://github.com/markdoc/docs/blob/main/pages/docs/nextjs.md Access the frontmatter object within your Markdoc content using the `$markdoc.frontmatter` variable. This example demonstrates displaying the frontmatter's title. ```markdown --- title: Using the Next.js plugin description: Integrate Markdoc into your Next.js app --- # {% $markdoc.frontmatter.title %} ``` -------------------------------- ### Extend Markdoc Configuration Source: https://github.com/markdoc/docs/blob/main/pages/docs/nextjs.md For advanced control over the Markdoc configuration, create a `/markdoc/config.js` file. This allows extending the config with additional data like records or utility functions, importing existing tags, nodes, and functions. ```javascript // markdoc/config.js import tags from './tags'; import nodes from './nodes'; import functions from './functions'; export default { tags, nodes, functions // add other stuff here }; ``` -------------------------------- ### Adding IDs to Headers with Annotations Source: https://github.com/markdoc/docs/blob/main/pages/docs/examples/index.md Demonstrates how to assign an ID to a Markdoc header using annotation syntax. This ID can then be used to link to the header, for example, in a table of contents. ```markdoc # My header {% #my-id %} ``` -------------------------------- ### Define Markdoc Tabs Tags Source: https://github.com/markdoc/docs/blob/main/pages/docs/examples/index.md Define the Markdoc tags for 'tabs' and 'tab' with their respective attributes and transformation logic. This setup is required before using the tags in your Markdoc documents. ```js import { Tag } from '@markdoc/markdoc'; const tabs = { render: 'Tabs', attributes: {}, transform(node, config) { const labels = node .transformChildren(config) .filter((child) => child && child.name === 'Tab') .map((tab) => (typeof tab === 'object' ? tab.attributes.label : null)); return new Tag(this.render, { labels }, node.transformChildren(config)); } }; const tab = { render: 'Tab', attributes: { label: { type: String } } }; /** @type {import('@markdoc/markdoc').Config} */ const config = { tags: { tabs, tab } }; ``` -------------------------------- ### Using Variables for Runtime Content Personalization Source: https://context7.com/markdoc/docs/llms.txt Demonstrates how to inject server-side data into Markdoc documents using variables. Variables are passed via `config.variables` and can be accessed using dot notation for nested objects, enabling personalized content rendering. ```javascript import Markdoc from '@markdoc/markdoc'; const doc = ` {% if $flags.showBeta %} ``` -------------------------------- ### Registering a Custom Attribute in Markdoc Config Source: https://github.com/markdoc/docs/blob/main/pages/docs/attributes.md Register your custom attribute type within the Markdoc `config` object. This example shows how to use the custom `DateTime` attribute for a tag. ```javascript import { DateTime } from './attribute-types/DateTime'; /** @type {import('@markdoc/markdoc').Config} */ const config = { tags: { 'tag-name': { render: 'YourComponent', attributes: { created: { type: DateTime, required: true } } } } }; ``` -------------------------------- ### Shorthand Attributes for ID and Class Source: https://github.com/markdoc/docs/blob/main/spec/index.md Shows shorthand attribute syntax for setting an ID and a class. ```markdoc {% #foo .bar %} ``` -------------------------------- ### Apply Shared Layout with Frontmatter Source: https://context7.com/markdoc/docs/llms.txt Use the '_app.js' file to apply a shared layout component and pass frontmatter data to it. ```javascript // pages/_app.js — apply a shared layout using frontmatter import Layout from '../components/Layout'; export default function App({ Component, pageProps }) { return ( ); } ``` -------------------------------- ### Defining Custom Attribute Types in Markdoc Configuration Source: https://github.com/markdoc/docs/blob/main/pages/docs/attributes.md Configure custom attribute types for tags to limit allowed values and enable validation. This example defines a 'type' attribute for a 'Callout' tag. ```javascript { render: 'Callout', children: ['paragraph', 'tag', 'list'], attributes: { type: { type: String, default: 'note', required: true, matches: ['caution', 'check', 'note', 'warning'], errorLevel: 'critical', }, } } ``` -------------------------------- ### Hash Value with String and Variable Keys Source: https://github.com/markdoc/docs/blob/main/spec/index.md Illustrates a hash value with both identifier and string keys, and a variable as a value. ```markdoc {% foo={key: "example value", "quoted key": $variable} %} ``` -------------------------------- ### Escaping Double Quotes in Attribute Strings Source: https://github.com/markdoc/docs/blob/main/pages/docs/attributes.md To include a literal double quote within a string attribute, escape it using \\. This example demonstrates escaping a double quote for a delimiter attribute. ```markdoc {% data delimiter="\"" /%} ``` -------------------------------- ### Parse and Configure Frontmatter Source: https://github.com/markdoc/docs/blob/main/pages/docs/frontmatter.md Loads frontmatter content using a specified parser (e.g., js-yaml) and configures Markdoc to use it as variables. ```javascript import yaml from 'js-yaml'; // or 'toml', etc. const frontmatter = ast.attributes.frontmatter ? yaml.load(ast.attributes.frontmatter) : {}; /** @type {import('@markdoc/markdoc').Config} */ const config = { variables: { frontmatter } }; ``` -------------------------------- ### Configure Global Variables Source: https://github.com/markdoc/docs/blob/main/pages/docs/variables.md Shows how to configure global variables in Markdoc using the config object. This includes conditional rendering based on flags and displaying user information. ```markdoc {% if $flags.my_feature_flag %} Username: {% $user.name %} {% /if %} ``` ```javascript const doc = ` {% if $flags.my_feature_flag %} Username: {% $user.name %} {% /if %} `; /** @type {import('@markdoc/markdoc').Config} */ const config = { variables: { flags: { my_feature_flag: true }, user: { name: 'Dr. Mark' } } }; const ast = Markdoc.parse(doc); const content = Markdoc.transform(ast, config); ``` -------------------------------- ### Markdoc Table with Rich Content Source: https://github.com/markdoc/docs/blob/main/pages/docs/tags.md Markdoc tables support rich content like code samples and lists within cells. This example includes a code block, a checkmark list, and a multi-line list item. ```markdown {% table %} * Foo * Bar * Baz --- * ``` puts "Some code here." ``` * {% list type="checkmark" %} * Bulleted list in table * Second item in bulleted list {% /list %} * Text in a table --- * A "loose" list with multiple line items * Test 2 * Test 3 --- * Test 1 * A cell that spans two columns {% colspan=2 %} {% /table %} ``` -------------------------------- ### Basic HTML Template for Markdoc Content Source: https://github.com/markdoc/docs/blob/main/pages/docs/examples/html.md A simple HTML structure to serve Markdoc content, including a placeholder for injected content and a script tag for client-side assets. ```html Markdoc: Create HTML Example {{ CONTENT }} ``` -------------------------------- ### Express Server with Markdoc Rendering Source: https://github.com/markdoc/docs/blob/main/pages/docs/examples/html.md Configures an Express server to handle Markdoc content requests, transforming and rendering it to HTML using custom schemas and components. ```javascript const express = require('express'); const app = express(); const callout = require('./schema/callout.markdoc'); const heading = require('./schema/heading.markdoc'); // [...](https://github.com/markdoc/docs/blob/dcba1a62be92097e3fd50c21e05fd6d2ea709312/examples/react-nodejs/server.js#L8-L14) app.get('/markdoc', (req, res) => { const ast = contentManifest[req.query.path]; const config = { tags: { callout }, nodes: { heading }, variables: {} }; const content = Markdoc.transform(ast, config); const rendered = Markdoc.renderers.html(content) || ''; const html = TEMPLATE.replace(/{{ CONTENT }}/, rendered); return res.send(html); }); app.listen(4242, () => { console.log(`Example app listening on port ${4242}`); }); ``` -------------------------------- ### Configure Markdoc with Custom Functions and Variables Source: https://context7.com/markdoc/docs/llms.txt Configure Markdoc to include custom functions ('includes', 'uppercase') and define variables ('countries', 'pageTitle'). This setup allows these functions and variables to be used within the Markdown document for dynamic content generation and conditional logic. ```javascript /** @type {import('@markdoc/markdoc').Config} */ const config = { functions: { includes, uppercase }, variables: { countries: ['US', 'JP', 'NG', 'AR'] } }; const doc = ` # {% uppercase($pageTitle) %} Available regions: {% if includes($countries, "US") %} 🇺🇸 United States {% /if %} {% if includes($countries, "JP") %} 🇯🇵 Japan {% /if %} {% if includes($countries, "DE") %} 🇩🇪 Germany {% /if %} `; const ast = Markdoc.parse(doc); const content = Markdoc.transform(ast, { ...config, variables: { ...config.variables, pageTitle: 'supported countries' } }); const html = Markdoc.renderers.html(content); //

SUPPORTED COUNTRIES

//

🇺🇸 United States 🇯🇵 Japan

``` -------------------------------- ### Client-Side Markdoc Rendering with React Source: https://github.com/markdoc/docs/blob/main/pages/docs/examples/react.md Fetches Markdoc content from the server and renders it using Markdoc's React renderer, mapping custom components like 'Callout'. ```javascript import React from 'react'; import Markdoc from '@markdoc/markdoc'; import { Callout } from './Callout'; export default function App() { const [content, setContent] = React.useState(null); React.useEffect(() => { (async () => { const response = await fetch( `/markdoc?` + new URLSearchParams({ path: window.location.pathname }), { headers: { Accept: 'application/json' } } ); if (response.status === 404) { setContent('404'); return; } const content = await response.json(); setContent(content); })(); }, []); if (content === '404') { return

Page not found.

; } if (!content) { return

Loading...

; } const components = { Callout }; return Markdoc.renderers.react(content, React, { components }); } ``` -------------------------------- ### Correct Variable Usage in Link Source: https://github.com/markdoc/docs/blob/main/pages/docs/variables.md Demonstrates the correct way to use a variable with a link by passing it to the `href` attribute of a custom `link` Tag. This is the recommended approach for dynamic link destinations. ```markdoc {% link href=$variable %}Link{% /link %} ``` -------------------------------- ### Including Partials in Markdoc Source: https://context7.com/markdoc/docs/llms.txt Shows how to include reusable Markdoc fragments (partials) in documents. Partials can be defined inline or loaded from disk. Variables can be passed scoped to a partial. ```javascript import Markdoc from '@markdoc/markdoc'; import fs from 'fs'; import path from 'path'; // Load partials from disk function loadPartials(dir) { return Object.fromEntries( fs.readdirSync(dir) .filter(f => f.endsWith('.md')) .map(f => [f, Markdoc.parse(fs.readFileSync(path.join(dir, f), 'utf8'))]) ); } /** @type {import('@markdoc/markdoc').Config} */ const config = { partials: { // Inline definition 'disclaimer.md': Markdoc.parse(`*All examples are for illustrative purposes only.*`), // Or load from disk: ...loadPartials('./markdoc/partials') } }; const doc = ` # SDK Reference {% partial file="disclaimer.md" /%} ## Authentication {% partial file="auth-header.md" variables={sdk: "Node.js", version: "3.0"} /%} `; const ast = Markdoc.parse(doc); const content = Markdoc.transform(ast, config); const html = Markdoc.renderers.html(content); ``` -------------------------------- ### Basic Markdoc Tag Usage Source: https://github.com/markdoc/docs/blob/main/spec/index.md Demonstrates a basic Markdoc tag with nested content. The opening and closing tags enclose a paragraph. ```markdoc {% example %} This paragraph is nested within a Markdoc tag. {% /example %} ``` -------------------------------- ### Using Custom Switch/Case Tags in Markdoc Source: https://github.com/markdoc/docs/blob/main/pages/docs/examples/index.md Illustrates the usage of custom 'switch' and 'case' tags in a Markdoc document to conditionally render content based on a primary value. ```markdoc {% switch $item %} {% case 1 %} Case 1 {% /case %} {% case 2 %} Case 2 {% /case %} {% /switch %} ``` -------------------------------- ### Import Markdoc with ESM Source: https://github.com/markdoc/docs/blob/main/pages/docs/getting-started.md Import the Markdoc library using ECMAScript Module (ESM) syntax. ```javascript import Markdoc from '@markdoc/markdoc'; ``` -------------------------------- ### Variable Syntax in Markdoc Source: https://github.com/markdoc/docs/blob/main/spec/index.md Demonstrates the syntax for defining and using variables in Markdoc. Variables can access nested data structures using dot notation and array indexing. ```markdoc {% foo=$bar.baz[10].qux %} ``` -------------------------------- ### Markdoc Annotations for Nodes Source: https://github.com/markdoc/docs/blob/main/pages/docs/syntax.md Demonstrates Markdoc annotations, used to pass attributes to nodes when HTML-like syntax is not applicable. Attributes are written in a separate `{%` and `%}` block following the node. ```markdoc {% table %} - Function {% width="25%" %} - Returns {% colspan=2 %} - Example {% align="right" %} {% /table %} ``` -------------------------------- ### Register Partials in Config Source: https://github.com/markdoc/docs/blob/main/pages/docs/partials.md Define partials by mapping file names to AST nodes in your Markdoc `config` object. This allows the default `partial` tag to locate and include the correct content. ```javascript /** @type {import('@markdoc/markdoc').Config} */ const config = { partials: { 'header.md': Markdoc.parse(`# My header`) } }; const doc = ` {% partial file="header.md" /%} `; const ast = Markdoc.parse(doc); const content = Markdoc.transform(ast, config); ``` -------------------------------- ### Include a Partial Source: https://github.com/markdoc/docs/blob/main/pages/docs/partials.md Use the `partial` tag to include content from another Markdoc file. ```markdoc {% partial file="header.md" /%} ``` -------------------------------- ### React Rendering with Markdoc Source: https://github.com/markdoc/docs/blob/main/pages/docs/render.md Render Markdoc content as React components. This involves transforming the document into a renderable tree and then using `Markdoc.renderers.react` with a mapping of tags to React components. ```javascript const tags = { callout: { render: 'Callout', attributes: {} } }; const doc = ` {% callout %} Attention, over here! {% /callout %} `; const ast = Markdoc.parse(doc); const content = Markdoc.transform(ast, { tags }); ``` ```jsx import Markdoc from '@markdoc/markdoc'; import React from 'react'; // or 'preact' function Callout({ children }) { return
{children}
; } function MyApp() { return Markdoc.renderers.react(content, React, { components: { Callout: Callout } }); } ``` -------------------------------- ### Format Markdoc AST to Source Source: https://context7.com/markdoc/docs/llms.txt Takes an AST `Node` (or one you construct programmatically) and serializes it back to Markdoc source text. Useful for generating Markdoc files from structured data or for pretty-printing documents. ```js const Markdoc = require('@markdoc/markdoc'); // Generate a Markdoc list from JSON data const coordinates = [ [34.0522, -118.2437], // Los Angeles [40.7128, -74.0060], // New York [48.8566, 2.3522] // Paris ]; const list = new Markdoc.Ast.Node( 'list', { ordered: false }, coordinates.map(point => new Markdoc.Ast.Node('item', {}, [ new Markdoc.Ast.Node('inline', {}, [ new Markdoc.Ast.Node('text', { content: point.join(', ') }, []) ]) ]) ) ); const output = Markdoc.format(list); console.log(output); // Output: // - 34.0522, -118.2437 // - 40.7128, -74.006 // - 48.8566, 2.3522 ``` -------------------------------- ### Implement Custom Layout in Next.js App Source: https://github.com/markdoc/docs/blob/main/pages/docs/nextjs.md Wrap your `Component` with a custom `Layout` component in `pages/_app.js` to create a consistent layout for all Markdown/Markdoc files. The layout can receive frontmatter as a prop. ```javascript // pages/_app.js import Layout from '../components/Layout'; export default function App({ Component, pageProps }) { return ( ); } ``` -------------------------------- ### Configure Custom Schema Path Source: https://github.com/markdoc/docs/blob/main/pages/docs/nextjs.md Specify a custom path for your Markdoc schema using the `schemaPath` option in `withMarkdoc`. ```javascript module.exports = withMarkdoc({ schemaPath: './path/to/your/markdoc/schema' })({ pageExtensions: // [...](https://nextjs.org/docs/api-reference/next.config.js/custom-page-extensions) }); ``` -------------------------------- ### Conditional Rendering with If/Else Tags Source: https://github.com/markdoc/docs/blob/main/pages/docs/tags.md Use the `if` and `else` tags for dynamic content rendering based on conditions. Note that only `undefined`, `null`, and `false` are considered falsey. ```markdown {% if true %} {% callout type="note" %} Tags are composable! {% /callout %} {% else /%} {% callout type="warning" %} Tags aren't composable! {% /callout %} {% /if %} ``` ```markdown {% if $myFunVar %} Only appear if $myFunVar! {% /if %} ``` ```markdown {% if $myFunVar %} Only appear if $myFunVar! {% else /%} This appears if not $myFunVar! {% /if %} {% if $myFunVar %} Only appear if $myFunVar! {% else $otherFunVar /%} This appears if not $myFunVar and $otherFunVar! {% else /%} This appears if not $myFunVar and not $otherFunVar {% /if %} ``` -------------------------------- ### Markdoc.format Source: https://context7.com/markdoc/docs/llms.txt Takes an AST `Node` (or one you construct programmatically) and serializes it back to Markdoc source text. Useful for generating Markdoc files from structured data or for pretty-printing documents. ```APIDOC ## `Markdoc.format(ast)` — Serialize an AST back to Markdoc source Takes an AST `Node` (or one you construct programmatically) and serializes it back to Markdoc source text. Useful for generating Markdoc files from structured data or for pretty-printing documents. ```js const Markdoc = require('@markdoc/markdoc'); // Generate a Markdoc list from JSON data const coordinates = [ [34.0522, -118.2437], // Los Angeles [40.7128, -74.0060], // New York [48.8566, 2.3522] // Paris ]; const list = new Markdoc.Ast.Node( 'list', { ordered: false }, coordinates.map(point => new Markdoc.Ast.Node('item', {}, [ new Markdoc.Ast.Node('inline', {}, [ new Markdoc.Ast.Node('text', { content: point.join(', ') }, []) ]) ]) ) ); const output = Markdoc.format(list); console.log(output); // Output: // - 34.0522, -118.2437 // - 40.7128, -74.006 // - 48.8566, 2.3522 ``` ``` -------------------------------- ### Parse and Transform Markdoc Content Source: https://github.com/markdoc/docs/blob/main/pages/index.md Import the Markdoc library to parse a Markdoc string into an Abstract Syntax Tree (AST), then transform the AST into content. Finally, render the content to HTML. ```javascript import Markdoc from '@markdoc/markdoc'; const doc = ` # Hello world. > My first Markdoc page `; const ast = Markdoc.parse(doc); const content = Markdoc.transform(ast); const html = Markdoc.renderers.html(content); ```