# Markdown templates

Use Markdown Templates when an application needs predictable Markdown composition with data bindings, conditions, or fragments. The renderer does not evaluate JavaScript or read files implicitly.

Start with the [Markdown Template tutorial](https://vitehub.dev/docs/markdown-template/get-started).

Keep input data explicit and validate it before rendering. Use the file integration only with explicit paths or `file:` URLs.

Prove interpolation, a false condition, a fragment, and a missing or invalid value. Compare the rendered Markdown with the expected output before sending it to email or an Agent.

`@vite-hub/markdown-template` fills Markdown templates with your data and conditions. It never runs JavaScript or reads files on its own. Use it for Agent Instructions, review prompts, and other generated documents that must keep your Markdown structure.

For a quick example, start with [Render your first Markdown template](https://vitehub.dev/docs/markdown-template/get-started).

## Install

You need Node.js 24.15 or newer.

```bash [Terminal]
pnpm add @vite-hub/markdown-template
```

## Import a template file

Put a `*.template.md` file next to the module that renders it. Importing the file returns an async render function.

```md [server/agents/reviewer/prompt.template.md]
# Review {{ data.pullRequest.number }}

Title: {{ data.pullRequest.title }}
```

```ts [server/agents/reviewer/agent.ts] fragment
import renderPrompt from './prompt.template.md'

const prompt = await renderPrompt({
  pullRequest: { number: 611, title: 'Refine navigation' },
})
```

- ViteHub only bundles `*.template.md` files you import directly. `@./partial.md` stays literal text and bundles nothing.
- Deployed apps never read `.template.md` source files from disk at runtime.
- The render function takes an optional `Record<string, unknown>` and returns `Promise<string>`.
- You can group templates in a folder like `./templates/`. ViteHub does not scan folders, so import each file you use. Several callers can import the same template from a shared path.

To pick a template at runtime, map the allowed names in TypeScript:

```ts [server/agents/reviewer/replies.ts] fragment
import renderFailure from './failure.template.md'
import renderSuccess from './success.template.md'

export const replies = {
  failure: renderFailure,
  success: renderSuccess,
} as const
```

Query imports must end with exactly `?markdown-template`. Compound queries and hash fragments are not supported. If another Vite plugin resolves a template import to a virtual ID, or to an ID with its own query or fragment, ViteHub leaves it to that plugin.

`vitehub()` sets up template imports automatically. In a modular Vite config, add `hubMarkdownTemplate()` from `@vite-hub/markdown-template/vite`. Both write module types to `.vitehub/types`, so include it in `tsconfig.json`.

To reuse a shared section, render it in TypeScript first and pass the string as a Markdown fragment.

## Render a template string

Pass a template string and a `data` object to `renderMarkdownTemplate()`. It returns Markdown. Inside the template, read values with Comark bindings like `{{ data.title }}`.

```ts
import { renderMarkdownTemplate } from 'vite-hub/markdown-template'

const template = `# Review {{ data.number }}

::if{:value="data.status" eq="ready"}
Review {{ data.title }}.
::else
Wait for the author.
::
::

:insert{:markdown="data.files"}`

const markdown = await renderMarkdownTemplate(template, {
  data: {
    number: 42,
    status: 'ready',
    title: '*Draft*',
    files: '- README.md\n- package.json',
  },
})
```

Here, `data.title` renders as literal text with escaped asterisks. `Insert` adds the file list as real Markdown.

## Bind values and attributes

`{{ data.path }}` inserts a string, number, or boolean as escaped text. Missing, null, or non-scalar values fail the render. Dotted paths read nested objects, such as `{ customer: { name: 'Acme' } }`. Paths read only own enumerable properties, plus array `length`.

Use Comark's colon-prefixed attributes for dynamic links and XML attributes:

```md
[Open review](){:href="data.reviewUrl"}

<policy :audience="data.audience">Review {{ data.title }}.</policy>
```

Build the full URL in TypeScript. ViteHub encodes characters that could break the Markdown. It rejects unsafe or unclear links, such as `javascript:`, `data:`, control characters, and malformed percent escapes. Bound XML attributes are escaped. Bindings and components also work in multiline XML blocks.

## Select conditional content

Use `:condition` for a truthy check, or pair `:value` with comparison props. A `:` prefix binds a data path or parses a JSON literal. Comparison props without `:` are plain strings. `condition` and `value` must have the `:` prefix: `::if{condition="data.trial"}` throws `MARKDOWN_TEMPLATE_R0024`.

```md
::if{:condition="data.enabled" :value="data.count" :gte="2" :lt="5"}
Show the small active batch.
::else-if{:value="data.status" eq="paused"}
The batch is paused.
::else
No active batch.
::
::
::
```

- `eq` and `neq` check strict equality.
- `gt`, `gte`, `lt`, and `lte` compare two numbers or two strings.
- Every comparison on a branch must match. A missing value or binding never matches, not even with `neq`.
- `:value` with no comparison is a truthy check. A falsy `:condition` always skips the branch.
- The first matching branch wins. ViteHub does not evaluate the other branches.
- Close each component, including `else-if` and `else`, with its own `::` line. Nested chains follow the same Comark rules.
- `else` takes no props and comes last.

Conditions never run JavaScript, call functions, or read globals. Compute compound logic in TypeScript and pass a boolean.

## Insert trusted Markdown

Use `{{ data.summary }}` for escaped text and `:insert{:markdown="data.summary"}` to keep Markdown formatting. For `summary: '**Ready**'`:

| Template | Result |
| --- | --- |
| `{{ data.summary }}` | Literal text `**Ready**`, with the asterisks escaped. |
| `:insert{:markdown="data.summary"}` | Markdown `**Ready**`, which renders as **Ready**. |

`Insert` is a ViteHub component in Comark syntax. `:markdown` reads a string from `data`. To insert headings, lists, or several paragraphs, put `:insert` on its own line with blank lines around it:

```md
:insert{:markdown="data.summary"}
```

The container form also works:

```md
::insert{:markdown="data.summary"}
::
```

Next to punctuation, Comark does not parse the colon shorthand. Use the paired tag form instead:

```md
Use (<Insert :markdown="data.policy"></Insert>).
```

- Every fragment must be a string.
- Inline fragments can only contain inline Markdown. Block Markdown in an inline position fails the render.
- Comark parses fragments as plain Markdown without evaluating bindings or components inside them.
- Comark may change the spelling of literal component attributes.
- `@./policy.md` stays literal. Render shared templates in TypeScript and pass the output as fragment data.

> **Warning**

Fragments are trusted input. The renderer does not make untrusted instructions safe for an Agent. Build or validate fragments before rendering them.

## Rendering behavior

Comark parses, escapes, renders components, and formats the output. It may change whitespace, quote style, or component syntax, so the output is not byte-for-byte identical to your source. Bindings and components inside code spans and code blocks stay literal.

The renderer does no file or network I/O. It has no loops, no JavaScript evaluation, and no public syntax-tree hooks. Prepare repeated content and compound conditions in TypeScript.

## Migrate existing templates

The new Comark syntax breaks old templates in direct render calls, imported files, Email, Agent Instructions, and progress summaries.

| Previous syntax | Comark syntax |
| --- | --- |
| `{{ name }}` | `{{ data.name }}` |
| `{{{ summary }}}` | `:insert{:markdown="data.summary"}` |
| `::if{enabled}` | `::if{:condition="data.enabled"}` |
| `::if{status === 'ready'}` | `::if{:value="data.status" eq="ready"}` |
| `::if{enabled && !draft}` | Compute `visible = enabled && !draft` in TypeScript, then use `::if{:condition="data.visible"}`. |
| `[Open]({{ url }})` | `[Open](){:href="data.url"}` |
| `<policy audience="{{ audience }}">` | `<policy :audience="data.audience">` |

`else-if` takes the same props as `if`. `else` takes none. Close every branch with `::`, then close the outer `if`. ViteHub does not translate old syntax. The render function and its `{ data }` option did not change.

A binding with an unrecognized root, such as `{{ name }}` or `:href="url"` on a link, fails with `MARKDOWN_TEMPLATE_BINDING_OUTSIDE_DATA`. Use `data.` to read template data. At build time, Email reports `MARKDOWN_TEMPLATE_BINDING_IN_CODE` as the cause when it finds a binding in inline code or a code block, including the old `{{ name }}` form. The Markdown Template renderer itself keeps such bindings as text.

A binding that fills a whole link destination, such as `[Open]({{ data.url }})`, fails with `MARKDOWN_TEMPLATE_R0033`. Comark does not parse that form as a link and would output the brackets as text.

## Render options

`renderMarkdownTemplate(template, options?)` returns `Promise<string>`. Options:

- `data?: Record<string, unknown>`, default `{}`.
- `plugins?: ComarkPlugin[]` adds Comark syntax handlers.

## Related pages

- [Agent Instructions](https://vitehub.dev/docs/agents/instructions)
- [Import paths](https://vitehub.dev/docs/reference/import-paths)

<!-- vitehub-docs:section-links -->
## In this section

- [Overview](https://vitehub.dev/raw/docs/markdown-template.md) (this page)
- [Get started](https://vitehub.dev/raw/docs/markdown-template/get-started.md)

Next: [MARKDOWN_TEMPLATE_R0002](https://vitehub.dev/raw/docs/markdown-template/diagnostics/markdown_template_r0002.md)

All pages: [llms.txt](https://vitehub.dev/llms.txt)
