Reuse & references›Include

core

Include

Paste a partial's content into the page during the preprocess phase, so data and snippet inside it resolve

Source

import Markdoc from '@markdoc/markdoc';
import type { Node } from '@markdoc/markdoc';
import type { PreprocessContext, PreprocessPage } from '@refrakt-md/types';
import { createContentModelSchema } from '../lib/index.js';
import { emitErrorNode } from '../data-emit.js';

const { Ast } = Markdoc;

export const MAX_INCLUDE_DEPTH = 16;

function preprocessInclude(tag: Node, page: PreprocessPage, ctx: PreprocessContext): Node[] | void {
	const partials = (ctx as { partials?: Record<string, unknown> }).partials;
	if (!partials) return;
	return resolveInclude(tag, page, ctx, partials, []);
}

function walkAndReplaceIncludes(
	node: Node,
	page: PreprocessPage,
	ctx: PreprocessContext,
	partials: Record<string, unknown>,
	stack: string[],
): void {
	if (!node.children) return;
	for (let i = 0; i < node.children.length; i++) {
		const child = node.children[i];
		if (child.type === 'tag' && child.tag === 'include') {
			const replacement = resolveInclude(child, page, ctx, partials, stack);
			node.children.splice(i, 1, ...replacement);
			i += replacement.length - 1;
			continue;
		}
		walkAndReplaceIncludes(child, page, ctx, partials, stack);
	}
}

function fail(ctx: PreprocessContext, page: PreprocessPage, message: string): Node[] {
	ctx.error(`include: ${message}`, page.url);
	return [emitErrorNode(`include error: ${message}`)];
}

function resolveInclude(
	tag: Node,
	page: PreprocessPage,
	ctx: PreprocessContext,
	partials: Record<string, unknown>,
	stack: string[],
): Node[] {
	const file = resolveValue(tag.attributes?.file, ctx.variables);
	if (typeof file !== 'string' || file.length === 0) {
		return fail(
			ctx,
			page,
			'the `file` attribute is required (an unresolvable variable reference resolves to empty)',
		);
	}

	if (stack.includes(file)) {
		return fail(ctx, page, `cycle — ${[...stack, file].join(' → ')}`);
	}
	if (stack.length >= MAX_INCLUDE_DEPTH) {
		return fail(
			ctx,
			page,
			`nested more than ${MAX_INCLUDE_DEPTH} deep — ${[...stack, file].join(' → ')}`,
		);
	}

	const source = partials[file];
	if (!source || typeof source !== 'object') {
		const known = Object.keys(partials).sort();
		const available =
			known.length > 0
				? ` Available: ${known.join(', ')}.`
				: ' No partials are registered for this site.';
		return fail(
			ctx,
			page,
			`"${file}" was not found in \`_partials/\` or any registered file root.${available}`,
		);
	}

	const bindings = resolveVariables(tag.attributes?.variables, ctx.variables);
	const pasted = (source as Node).children ?? [];
	const children = pasted.map((child) => cloneWithBindings(child, bindings));

	if (children.length > 0) {
		const container = new Ast.Node('document', {}, children);
		walkAndReplaceIncludes(container, page, ctx, partials, [...stack, file]);
		return container.children;
	}
	return children;
}

function cloneWithBindings(node: Node, bindings: Record<string, unknown>): Node {
	const attributes: Record<string, unknown> = {};
	for (const [key, value] of Object.entries(node.attributes ?? {})) {
		attributes[key] = substitute(value, bindings);
	}
	const children = (node.children ?? []).map((child) => cloneWithBindings(child, bindings));
	const copy = new Ast.Node(node.type, attributes, children, node.tag);
	if (node.lines) copy.lines = node.lines;
	if (node.location) copy.location = node.location;
	copy.inline = node.inline;
	if (node.annotations?.length) copy.annotations = node.annotations;
	if (node.slots && Object.keys(node.slots).length > 0) {
		copy.slots = Object.fromEntries(
			Object.entries(node.slots).map(([k, v]) => [k, cloneWithBindings(v, bindings)]),
		);
	}
	return copy;
}

function substitute(value: unknown, bindings: Record<string, unknown>): unknown {
	if (!value || typeof value !== 'object') return value;
	const node = value as { $$mdtype?: string; path?: unknown };
	if (node.$$mdtype === 'Variable' && Array.isArray(node.path) && node.path.length > 0) {
		const [root, ...rest] = node.path as string[];
		if (!(root in bindings)) return value;
		let current: unknown = bindings[root];
		for (const segment of rest) {
			if (current === null || current === undefined) return '';
			current = (current as Record<string, unknown>)[segment];
		}
		return current === null || current === undefined ? '' : current;
	}
	return value;
}

function resolveVariables(
	raw: unknown,
	pageVariables: Record<string, unknown> | undefined,
): Record<string, unknown> {
	if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
	const out: Record<string, unknown> = {};
	for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
		out[key] = resolveValue(value, pageVariables);
	}
	return out;
}

function resolveValue(value: unknown, variables: Record<string, unknown> | undefined): unknown {
	if (value === undefined || value === null) return '';
	if (typeof value !== 'object') return value;
	const node = value as { $$mdtype?: string; path?: unknown };
	if (node.$$mdtype === 'Variable' && Array.isArray(node.path)) {
		let current: unknown = variables;
		for (const segment of node.path as string[]) {
			if (current === null || current === undefined) return '';
			current = (current as Record<string, unknown>)[segment];
		}
		return current === null || current === undefined ? '' : current;
	}
	if (node.$$mdtype === undefined) return value;
	return '';
}

export const include = createContentModelSchema({
	attributes: {
		file: {
			type: String,
			required: true,
			description:
				'Partial to paste, by the same key `{% partial %}` uses — a path under the site\'s `_partials/` (e.g. "attrs.md") or a namespaced file root ("shared:attrs.md").',
		},
		variables: {
			type: Object,
			required: false,
			description:
				'Bindings substituted into the pasted AST at paste time, e.g. variables={q: "rune:card"} makes `$q` inside the file that string. Unlike `partial`, this is substitution rather than a transform-time scope, so bound values reach preprocessor attributes such as `{% data where=$q %}`.',
		},
	},
	contentModel: { type: 'sequence', fields: [] },
	preprocess: preprocessInclude,
	transform(_resolved, _attrs) {
		throw new Error(
			'{% include %} reached the transform phase unresolved — its preprocess hook was not ' +
				'wired through. Ensure the content pipeline runs registered `preprocess` hooks before ' +
				"`Markdoc.transform` (include pastes its file's AST).",
		);
	},
});

View packages/runes/src/tags/include.ts on GitHub

{% include %} pastes a shared file's content into the page, like {% partial %} — but early enough that {% data %} and {% snippet %} inside that file resolve.

Every rune page on this site ends with one, and the Attributes table at the foot of this page is its output:

{% include file="rune-attributes.md" variables={r: "rune:include"} /%}

The file, _partials/rune-attributes.md, reads its rows with {% data %}, so a {% partial %} could not pull it in. It is shown here as a fence because a second copy of it would add a second attribute table to this page.

Both runes read the same _partials/ directory and the same file roots, so moving between them changes the call site and nothing else. A file's location does not depend on its contents.

When to use which

Reach for {% partial %} first. It is Markdoc's own tag, it works the same way in every Markdoc project, and it covers the common case: a reusable chunk of content, with or without variables.

Reach for {% include %} when the file contains {% data %} or {% snippet %}. Those are refrakt's, and they resolve in a phase Markdoc does not know about — see below. include is otherwise a strict superset, so switching costs nothing but the tag name.

partialinclude
Whose tagMarkdoc'srefrakt's
Reads _partials/ and file rootsyesyes
Takes variablesyesyes
Contains data / snippetno — the build stopsyes
Sees the page's own variablesno — its scope replaces themyes, for anything it does not bind

The problem it solves

Markdoc expands {% partial %} during the transform phase. refrakt resolves data and snippet in a preprocess phase that runs before that, walking the page's syntax tree — and a partial's content is not in that tree yet when it runs. So the tag survives, reaches its own transform, and the build stops:

{% data %} reached the transform phase unresolved.

If this file is pulled in with {% partial %}: use {% include %} instead.

include resolves in the preprocess phase too, and splices the file's content into the page where the tag was. The phase walks the page in tree order and continues into what was just pasted, so a data or snippet in the file resolves exactly as if it had been typed on the page.

Setup

There is no separate setup. Put the file in _partials/ exactly as you would for a partial, and reference it by the same key.

content/
├── _partials/
│   ├── cta.md                  ← plain content: use {% partial %}
│   └── attribute-table.md      ← contains {% data %}: use {% include %}
└── runes/
    └── card.md
{% include file="attribute-table.md" /%}
{% include file="shared/attribute-table.md" /%}
{% include file="shared:attribute-table.md" /%}

Passing variables

variables works the way it does on partial — a map of bindings the file reads with $. The file included at the top of this page opens like this:

{% data src="site/content/_data/rune-attributes.json" root="own" where=$r headers="Attribute, Type, Required, Description" %}
{% code %}{% $row.name %}{% /code %}
---
{% code %}{% $row.type %}{% /code %}
---
{% if $row.required %}✓{% else /%}—{% /if %}
---
{% $row.description %}
{% /data %}

and the call passes variables={r: "rune:include"}, which the file reads as $r.

The difference from partial is where the binding lands. A partial's variables are a scope the transform reads, which is exactly the phase a preprocessor rune never reaches. An include substitutes them into the content as it pastes, so a binding reaches {% data where=$r %} — the case above.

One consequence worth knowing: variables the include does not bind are left alone rather than blanked, so {% $page.slug %} inside an included file still resolves against the page. A partial cannot do that — its scope replaces the variable surface.

Nesting

An included file can include another. Depth is bounded, and a cycle is reported by name rather than overflowing the stack:

include error: cycle — a.md → b.md → c.md → a.md

Content boundaries

The pasted content lands as siblings at the call site, not wrapped in a container. That is what lets a parent rune read it:

{% accordion %}
	{% include file="faq-items.md" /%}
{% /accordion %}

The accordion sees the included headings as its own children and builds one item per heading. Had the content been wrapped, {% section %} and {% grid %} would consume it and the items would vanish with no error — so it is not.

Errors

Failures render on the page as a caution callout and record a build error; one bad include does not take down the build.

MessageCause
"x.md" was not found in _partials/ or any registered file rootNo such key. The message lists what is available.
the \file` attribute is required`Omitted, or a variable reference that resolved to empty.
cycle — a.md → b.md → a.mdA file includes itself, directly or through a chain.
nested more than 16 deepA chain of distinct files past the depth bound.

Attributes

AttributeTypeRequiredDescription
filestring✓Partial to paste, by the same key `{% partial %}` uses — a path under the site's `_partials/` (e.g. "attrs.md") or a namespaced file root ("shared:attrs.md").
variablesObject—Bindings substituted into the pasted AST at paste time, e.g. variables={q: "rune:card"} makes `$q` inside the file that string. Unlike `partial`, this is substitution rather than a transform-time scope, so bound values reach preprocessor attributes such as `{% data where=$q %}`.

Universal attributes

bg

The background layer: image, video, gradient, flat overlay wash and legibility scrim, in a single injected layer behind the rune's content.

AttributeTypeRequiredDescription
bgstring—Background preset applied to this block
bg-fromstring—Gradient start colour — a semantic token name (→ var(--rf-color-*))
bg-gradient"to-t" | "to-b" | "to-l" | "to-r" | "to-tr" | "to-br" | "to-bl" | "to-tl"—Gradient direction (bounded named set)
bg-gradient-type"linear" | "radial" | "conic"—Gradient type
bg-tostring—Gradient end colour — a semantic token name
bg-viastring—Optional middle gradient stop — a semantic token name
scrim"top" | "bottom" | "left" | "right" | "none"—Scrim direction (heaviest edge); presence turns the scrim on, "none" opts out of the default cover scrim
scrim-blur"none" | "sm" | "md" | "lg"—Frost scrim blur amount
scrim-strength"sm" | "md" | "lg"—Gradient scrim strength
scrim-tone"dark" | "light"—Whether the scrim darkens (for light text) or lightens (for dark text)
scrim-type"gradient" | "frost"—Scrim treatment: gradient (default) or frost (backdrop blur)
elevation

How far the rune sits off the page, from sunken to overlay. The theme decides what each step looks like.

AttributeTypeRequiredDescription
elevation"sunken" | "flush" | "flat" | "raised" | "floating" | "overlay" | "none" | "sm" | "md" | "lg"—Surface depth, from sunken to overlay. Deprecated: none, sm, md and lg (read as flat, raised, raised and floating)
inset

Internal padding override.

AttributeTypeRequiredDescription
inset"flush" | "tight" | "default" | "loose" | "breathe"—Inner padding of this block
motion

Scroll-reveal entrance. You choose its character; the theme decides how it moves.

AttributeTypeRequiredDescription
reveal"none" | "fade" | "slide" | "scale" | "blur"—Scroll-reveal entrance character (none|fade|slide|scale|blur); the theme owns the choreography
staggerboolean—Cascade this block's items in as it reveals (no-op on single-child runes)
spacing

Block-level rhythm override.

AttributeTypeRequiredDescription
spacing"flush" | "tight" | "default" | "loose" | "breathe"—Vertical spacing above and below this block
substrate

Generated pattern fills behind the content, drawn by the theme.

AttributeTypeRequiredDescription
substrate"dots" | "grid" | "lines" | "cross" | "checker" | "none"—Generated surface pattern
substrate-fill"inherit" | "inset"—Surface fill the pattern sits on (full colour stays with tint)
substrate-opacity"sm" | "md" | "lg"—Pattern ink strength
substrate-size"sm" | "md" | "lg"—Pattern cell size
substrate-target"self" | "media"—Which surface the pattern fills (overrides the rune/theme default)
tint

Per-rune colour override: a named tint from the theme registry, with inline per-token overrides layered on top.

AttributeTypeRequiredDescription
tintstring—Color tint preset applied to this block
tint-mode"auto" | "dark" | "light"—Whether the tint adapts to auto, dark, or light mode
width

The track a block rune occupies.

AttributeTypeRequiredDescription
width"compact" | "narrow" | "content" | "wide" | "full"—Maximum width constraint for this block
Not availableWhy
dropcap, readingthis rune declares no prose body
framethis rune declares neither a `frameTarget` nor a media section
prominencethis rune has no page-section header or featured quotation

See also

  • Partials — the shared _partials/ directory, file roots, and variables
  • data — the rune that most often forces this choice
  • snippet — the other preprocessor rune