Skip to content

Variables

Variables let you customize your Markdoc documents at runtime.

Here I am rendering a custom {% $variable %}

As server-side data changes, you can present it in real time by re-rendering the page. Each re-render uses the variable's latest value.

(Some templating languages let variables change during rendering, letting you use them in things like for loops. Markdoc doesn't do this, but it does offer alternative ways to do the same job.)

Global variables

You can pass variables in several ways. The simplest is through the variables field on your config object.

const doc = `
{% if $flags.my_feature_flag %}
Username: {% $user.name %}
{% /if %}
`;

/** @type {import('@markdoc/markdoc').Config} */
const config = {
  variables: {
    flags: {
      my_feature_flag: true
    },
    user: {
      name: 'Dr. Mark'
    }
  }
};

const ast = Markdoc.parse(doc);
const content = Markdoc.transform(ast, config);

Variables in partials

You can also pass variables to a partial. To do this, set the variables attribute:

{% partial variables={sdk: "Ruby", version: 3} file="header.md" /%}

Access the value within your partial file the same way you would a regular variable:

SDK: {% $sdk %}
Version: {% $version %}

Alternatives

Variables are immutable during page rendering. This keeps rendering behavior consistent and fast. But it means there are some tasks that you should use an alternative for:

Caveats

Markdoc doesn't support passing variables to certain nodes, such as the href of a link Node. Instead, pass your variable to the href attribute of a custom link Tag.

Incorrect

[Link]({% $variable %})

Correct

{% link href=$variable %}Link{% /link %}

Next steps