Skip to content

Functions

Functions enable you extend Markdoc with custom utilities, which let you transform your content and variables at runtime.

Built-in functions

Markdoc comes out-of-the-box with six built-in functions: equals, and, or, not, default, and debug.

FunctionReturnsExampleDescription
equalsbooleanequals($myString, 'test')Performs common boolean operation
andbooleanand($boolean1, $boolean2)Performs common boolean operation
orbooleanor($boolean1, $boolean2)Performs common boolean operation
notbooleannot(or($boolean1, $boolean2))Performs common boolean operation
defaultmixeddefault($variable, true)Returns the second parameter if the first parameter is undefined
debugstringdebug($anyVariable)Serializes the value as JSON, for debugging

And/Or/Not

Use these functions with the if tag to perform boolean operations and render the content when the condition is met.

Warning

Unlike JavaScript, Markdoc only considers undefined, null, and false to be falsey.

This is always shown
{% if and(not($a), or($b, $c)) %}
This is shown only if $a is falsy and either $b or $c is true.
{% /if %}

Equals

Use the equals function to compare a variable against a given value. This function uses JavaScript's strict equality semantics, and is only used for primitive types.

{% if equals($myVar, "test") %}
The variable $myVar is equal to the string "test".
{% /if %}

Default

This function is useful to set a value for a variable that might not exist.

{% if default($showPrompt, true) %}
Hey there!
{% /if %}

Debug

This function simply renders the value as a serialized JSON value in the document. This can be useful for determining what value is in a variable.

{% debug($myVar) %}

Creating a custom function

To extend Markdoc with your own functions, first create custom function definitions:

const includes = {
  transform(parameters) {
    const [array, value] = Object.values(parameters);

    return Array.isArray(array) ? array.includes(value) : false;
  }
};

const uppercase = {
  transform(parameters) {
    const string = parameters[0];

    return typeof string === 'string' ? string.toUpperCase() : string;
  }
};

Then, pass the functions to your config object.

/** @type {import('@markdoc/markdoc').Config} */
const config = {
  functions: {
    includes,
    uppercase
  }
};

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

Finally, call the functions within your Markdoc content

{% if includes($countries, "AR") %} πŸ‡¦πŸ‡· {% /if %}
{% if includes($countries, "AU") %} πŸ‡¦πŸ‡Ί {% /if %}
{% if includes($countries, "ES") %} πŸ‡ͺπŸ‡Έ {% /if %}
{% if includes($countries, "JP") %} πŸ‡―πŸ‡΅ {% /if %}
{% if includes($countries, "NG") %} πŸ‡³πŸ‡¬ {% /if %}
{% if includes($countries, "US") %} πŸ‡ΊπŸ‡Έ {% /if %}

Next steps