contents: Rearrange content in your documents

Overview

Sometimes it’s useful to define content in your document in an order that is different from the order in which you want the document to be presented. Although you can develop Lua filters that solve this kind of problem, Quarto 1.6 and later offers a simpler solution that works in many use cases: the {{< contents >}} shortcode.

Here’s a minimal example of how it can be used:

## A section

Here we define a plot.

```{python}
#| echo: false
#| label: a-cell
import matplotlib.pyplot as plt
plt.plot([1,2,3])
```

## Another section

Here we use the plot, inside a callout:

::: callout-note

## Note the following plot

{{< contents a-cell >}}

:::

The code above produces the following output:

A screenshot of the resulting document

Why

{{< contents >}} increases your freedom in defining the document the most comfortable way you can. It can simply because you want to write the code in the middle of a different explanation, but you want to result to appear elsewhere.

One particularly important reason is that Jupyter notebooks do not allow code cells to “nest” inside markdown, and many of Quarto’s features are defined in terms of fenced divs, Markdown that looks like this:

::: {#div-id .class1 .class2 key1="value1"}

The contents of a fenced div

:::

In this case, authoring Quarto documents with .ipynb would otherwise be cumbersome. {{< contents >}} allows you to use the contents of a code cell inside a Markdown cell without having to split the Markdown in a way that Jupyter Notebook, Jupyter Lab, and Quarto’s JupyterLab extensions don’t know how to render.

How it works

Quarto takes {{< contents <id> >}} shortcodes to mean “take the contents of cell with id id from the document and place it here instead”.

The most natural use case is for code cells, but {{< contents >}} also works with any document divs or spans, and uses the div and span ids.

Caution

The id of the following div is a-div, and not #a-div. As a result, refer to it in a contents shortcode as {{< contents a-div >}}.

::: {#a-div}

The contents of a fenced div

:::

When using divs and spans with {{< contents >}}, make sure that you’re moving them to appropriate locations. Specifically, a div cannot be placed in the middle of a paragraph; that requires a span. As a result, you cannot do the following:

```{python}
#| label: a-cell
print("some code")
```

The output of the code cell is {{< contents a-cell >}}. Etc.

If this is the style of organization you wish to use, you need to write the code inline, and wrap it in a span:

We will define some values here. [`{python} "some code"`]{#a-span}

The output of that inline code cell is {{< contents a-span >}}. Etc.

Limitations

Currently, {{< contents >}} itself does not work inside code elements. We may lift that limitation in the future.