---
title: Templates and filling
description: Parse, fill, and instantiate Mustache-style Markdown and notebook templates.
order: 5
---
Template evaluation follows Mustache data dispatch spelled by [`TemplateDelimiter`](parse.md#templatedelimiter) sigils (the value's type selects conditional, iteration, or scoping; declarative tokens never execute). A range is legal when its open and close markers are siblings in the parsed MDHTML DOM, and substituted values re-render recursively up to a depth cap.

```python
src = "Hello {{name}}:\n\n{{#items}}\n- {{.}}\n{{/items}}\n"
assert len(tokens(src)) == 4
assert fill_md(src, {"name": "Ada", "items": ["parse", "export"]}) == "Hello Ada:\n\n- parse\n- export\n"
```

[`tokens`](fill.md#tokens) inventories every template token in document order; [`fill_md`](fill.md#fill_md) is a pure text-to-text renderer; [`instantiate`](fill.md#instantiate) loads frontmatter `formdata:` (preserving scalars as `str` except booleans) and executes `{python}` blocks in a shared `execnb` shell (`mdhtml[fill]`); [`instantiate_nb`](fill.md#instantiate_nb) runs participating `#| eval: true` code cells of a notebook or dialog `.ipynb`. Scanning and previewing untrusted templates is safe, whereas [`instantiate`](fill.md#instantiate) and [`instantiate_nb`](fill.md#instantiate_nb) execute participating code. Strict mode (`strict=True`) raises `ValueError` on missing/unused fields or ill-formed ranges; executing `{python}` blocks without `execnb` raises `ImportError`.

## tokens

```python
def tokens(
    src:str, # Markdown source (spans index its newline-normalized text)
    templates=None, # `TemplateDelimiter`s, default `mdhtml.mustache.MUSTACHE`
)->list:
```

*Every template token in `src`, in document order: one dict per token with `start`/`end` byte span, `line` (1-based), `syntax`, `source`, `body`, `kind`, `name`, `inverted`, `block` form, `extent` (the span grown to the whole line for a standalone marker line), and `group` (an id shared by tokens whose carrier elements are DOM siblings, `None` when placement is unknown). The shared inventory behind fill, previews, and docx field binding: tokens map 1:1 in document order to the rendered fragment's carrier elements.*

## fill\_md

```python
def fill_md(
    src:str, # Markdown template source
    data:dict, # Field values; mappings and lists drive shape, scalars substitute
    strict:bool=True, # Raise on missing/unused fields and ill-formed ranges (else defer and warn)?
    filled=None, # Decoration callback `(name, value) -> str`, default `str(value)`
    templates=None, # `TemplateDelimiter`s, default `mdhtml.mustache.MUSTACHE`
)->mdhtml.md.Md:
```

*Render template tokens in `src` from `data`: the pure engine, no execution, no gathering, no files.*

## frontmatter\_data

```python
def frontmatter_data(
    src:str
)->dict:
```

*Extract the `formdata:` mapping from a leading YAML frontmatter block (scalars kept as `str` except `bool`; returns `{}` when absent).*

## instantiate

```python
def instantiate(
    src:str, # Markdown template source, frontmatter and `{python}` blocks included
    data:dict | None=None, # Per-matter values, merged over frontmatter `formdata:`
    strict:bool=True, # Raise on missing/unused fields and ill-formed ranges (else defer and warn)?
    dest=None, # Optional path to also write the result to
    filled=None, # Decoration callback `(name, value) -> str`, default `str(value)`
    templates=None, # `TemplateDelimiter`s, default `mdhtml.mustache.MUSTACHE`
)->mdhtml.md.Md:
```

*Instantiate a template: gather data, execute `{python}` blocks (the one execution point), weave their outputs, render, optionally write `dest`.*

## instantiate\_nb

```python
def instantiate_nb(
    fname, # Notebook/dialog `.ipynb` path or `Dialog`: its code cells are the template's executable blocks
    data:dict | None=None, # Per-matter values, merged over frontmatter `formdata:`
    strict:bool=True, # Raise on missing/unused fields and ill-formed ranges (else defer and warn)?
    dest=None, # Optional path to also write the result to
    filled=None, # Decoration callback `(name, value) -> str`, default `str(value)`
    templates=None, # `TemplateDelimiter`s, default `mdhtml.mustache.MUSTACHE`
)->mdhtml.md.Md:
```

*Instantiate a dialog: run its participating code cells (the `eval` cascade, opt-in by default), weave their outputs, fill tokens*
