Language guide · 02

Logic

Include content conditionally, choose fallback values, and repeat Markdown over arrays—all with a deliberately small template language.

Conditionals

Use {% if %} to include content only when an expression is true. Add elseif and else for alternative branches.

status.mdKNAP
1{% if status == "published" %}2Published on {{ published | date:"YYYY-MM-DD" }}3{% elseif status == "draft" %}4Draft5{% else %}6Unknown status7{% endif %}

Comparison and logical operators

OperatorMeaningExample
==Equal tostatus == "draft"
!=Not equal tostatus != "archived"
> < >= <=Ordered comparisonprice >= 100
containsString substring or array membertags contains "reference"
and / &&Both sides are trueauthor and published
or / ||Either side is truedraft or archived
not / !Negate an expressionnot hidden

Use parentheses to make grouped expressions explicit.

1{% if (premium or featured) and published %}2Featured reading3{% endif %}

Truthiness

false, null, undefined, an empty string, 0, and an empty array are falsy. Other values are truthy.

1{% if content %}2{{ content }}3{% endif %}

Fallback values

The ?? operator returns the first truthy value and has the lowest precedence, so filters run before the fallback check.

1{{ title ?? headline ?? "Untitled" }}2{{ title | upper ?? "UNTITLED" }}

Loops

Use {% for %} to render a block once for every value in an array.

1{% for tag in tags %}2- #{{ tag | kebab }}3{% endfor %}

Loops can iterate over variables supplied by the host, values created with set, and arrays found in nested data.

Loop values

ValueDescription
loop.indexCurrent iteration, starting at 1
loop.index0Current iteration, starting at 0
loop.firstTrue on the first iteration
loop.lastTrue on the last iteration
loop.lengthTotal number of items
item_indexBackwards-compatible 0-based index named after the iterator
1{% for author in authors %}2{{ loop.index }}. {{ author.name }}{% if loop.last %}.{% else %};{% endif %}3{% endfor %}

Combine and nest logic

Conditions, loops, and assignments can be nested to work with structured data.

1{% for section in sections %}2## {{ section.title }}3{% for item in section.items %}4{% if item.active %}- {{ item.name }}{% endif %}5{% endfor %}6{% endfor %}