MDX Runtime Helpers

Methanol automatically injects a lightweight runtime context into every MDX file, facilitating the creation of dynamic content and simplified template integration.

Context Variables

The following helpers are globally available within MDX pages:

# {frontmatter.title ?? ctx.page.title}

Current Route: {ctx.routePath}

Context Structure

Key properties available on the ctx object:

Note: You typically do not need to use ctx.withBase() for theme.sources or static files in public/, as Methanol resolves these at build time. However, it is a useful safeguard for URLs generated dynamically via JavaScript in development environments.

ctx.site

ctx.site is a snapshot of site-level metadata and build flags, including:

ctx.page Metadata Object

ctx.page provides comprehensive metadata for the current page. The full schema includes:

Note: Directory index routes always include a trailing slash in routePath (e.g., /guide/). ctx.page.getSiblings() is injected at runtime to facilitate previous/next navigation.

Usage Example:

{ctx.page.title}
{ctx.page.frontmatter?.excerpt}

ctx.pages List

ctx.pages is a flat array containing metadata objects (matching the ctx.page schema) for navigation. It excludes pages marked with exclude: true, and it omits /404 and /offline unless those pages are explicitly set to hidden: false. Hidden pages may still appear here, but ctx.pagesTree will filter them out.

This is ideal for generating custom indices, sitemaps, or manual navigation structures:

<ul>
  {ctx.pages.map((page) => (
    <li><a href={page.routeHref || page.routePath}>{page.title}</a></li>
  ))}
</ul>

ctx.pagesTree Hierarchy

ctx.pagesTree represents the navigation hierarchy for the current root context (adhering to isRoot and hidden rules). Node structure:

Use this to construct navigation UIs that mirror the sidebar structure:

{ctx.pagesTree.map((node) => (
  <div>{node.title || node.name}</div>
))}

ctx.getSiblings Helper

ctx.getSiblings() retrieves the preceding and succeeding pages in the current navigation sequence. It respects the active navigation root and visibility rules, ensuring consistency with the sidebar order.

{(() => {
  const siblings = ctx.getSiblings()
  if (!siblings) return null
  return (
    <nav>
      {siblings.prev ? <a href={siblings.prev.routeHref || siblings.prev.routePath}>Previous: {siblings.prev.title}</a> : null}
      {siblings.next ? <a href={siblings.next.routeHref || siblings.next.routePath}>Next: {siblings.next.title}</a> : null}
    </nav>
  )
})()}

rawHTML Utility

The rawHTML helper allows for the injection of unescaped HTML. This is particularly useful for inline scripts or specific markup that must remain unsanitized.

{rawHTML('<span class="badge">Beta</span>')}
{rawHTML`<div data-banner="true">Banner</div>`}

rawHTML supports reactivity via signals and standard template interpolation.