Documentation

Template Syntax Reference

This guide covers Clarity expressions, directives, operators, and control structures.

Syntax Overview

Clarity uses two primary delimiters:

Syntax Purpose
{{ ... }} Output expressions (print values)
{% ... %} Directives (control flow, logic, inheritance)
{# ... #} Comments (not rendered in output)

Whitespace Control

Place - next to a delimiter to trim whitespace on that side: {%- trims before the tag and -%} after it. Only spaces, tabs, and newlines are removed.

{% for item in items %}
  <li>{{ item }}</li>
{% endfor %}

Without trimming, directive lines can leave blank lines. Add markers to remove them:

{% for item in items -%}
  <li>{{ item }}</li>
{%- endfor %}

The same markers work on output tags ({{- x -}}) and comments ({#- c -#}).

Whitespace between tags

Whitespace between tags on a line that already has content is kept as one space:

<div class="card {{ cardClass ?? '' }} {{ bodyClass ?? '' }}">

This renders class="card card-wide is-active". The same applies next to directives:

<div class="card {% if wide %}card-wide{% endif %} {{ bodyClass ?? '' }}">

When wide is true, this also renders class="card card-wide is-active". Comments count as tags too. Use trim markers to remove an unwanted gap.

A line break between output tags is also a gap: {{ a }}\n{{ b }} renders A B. Line breaks next to directives remain layout and disappear.

Whitespace at the start of a line is indentation and is dropped. This avoids adding spaces to an {% extends %} / {% block %} preamble and preserves <pre> indentation.

Output Expressions

Basic Output

Use double curly braces to output a value:

<p>{{ message }}</p>
<h1>{{ pageTitle }}</h1>

Auto-Escaping

Output is HTML-escaped automatically:

{{ userInput }}
<!-- If userInput = "<script>alert('xss')</script>" -->
<!-- Outputs: &lt;script&gt;alert('xss')&lt;/script&gt; -->

To output raw HTML, use the raw filter:

{{ trustedHtml |> raw }}

Variable Access

Access operators specify the expected value type: . reads object properties, while : and [] read array keys. Clarity emits the corresponding access directly without converting objects to arrays.

Syntax Meaning Emits
a.b.c object property (static) $vars['a']->b->c
a{expr} object property (dynamic) $vars['a']->{<expr>}
items[expr] array index $vars['items'][<expr>]
a:b:c array key (static) $vars['a']['b']['c']
$a->b PHP-style alias for . $vars['a']->b
$a->{<expr>} PHP-style alias for . $vars['a']->{<expr>}
a?.b a?[i] a?{k} a?:k optional receiver isset(…) ? … : null / …?->b
<!-- Object properties -->
{{ user.name }} {{ user.address.city }}

<!-- Array keys -->
{{ config:version }} {{ item:meta:title }}

<!-- Array index (dynamic) -->
{{ items[0] }} {{ items[index] }}

<!-- Dynamic property -->
{{ user{fieldName} }}

<!-- Mixed: array of objects -->
{{ users[0].profile.avatar }} {{ data:items[currentIndex].title }}

Strictness

Using an operator for the wrong type raises an error:

{% set user = { name: "Alice" } %}   {# a MAP (PHP array) #}
{{ user.name }}     {# ERROR: Cannot read property "name" on array #}
{{ user:name }}     {# CORRECT #}

The same keys can be stated as an object literal when . is what you want to write — see Object literals:

{% set user = (object) { name: "Alice" } %}
{{ user.name }}     {# CORRECT #}

A missing key or property raises ClarityException with the template and line.

When strictVariables is denied, missing names, keys, properties, and intermediate values resolve to null and produce a warning with the template line. Wrong-type access remains an error; for example, user.name on an array or user['x'] on an object.

Optional access

? makes the value before it optional; access after it remains strict, so a missing member still raises an error:

{{ user?.name }}          {# fine when `user` is absent/null #}
{{ items?[0] }}           {# fine when `items` is absent/null #}
{{ user?.address?.city }} {# fine when `user` OR `address` is absent/null #}

? guards only the value to its left:

Expression user absent/null user present, name missing
user.name ERROR ERROR
user?.name null ERROR
user.name ?? 'x' ERROR 'x'
user?.name ?? 'x' 'x' 'x'

Clarity emits different guards for array and object access:

Expression Emits
a?:b (isset($vars['a']) ? $vars['a']['b'] : null)
a?.b (isset($vars['a']) ? $vars['a']->b : null)
a?.b?.c (isset($vars['a']) ? $vars['a']->b : null)?->c
a?:b?:c a === null test that binds the receiver to a temporary

Each form uses the shortest guard that tolerates an absent receiver.

Array access: items?[9] ?? 'fb' cannot suppress a missing index because the guarded read happens before ??. Use items[9] ?? 'fb' instead. Object access composes with ?? through PHP's ?->.

The dollar sigil

Clarity accepts PHP-style variable syntax in templates, including $-prefixed property access and array indexing.

PHP-style -> access requires $:

{{ $user->name }}    {# legal, identical to {{ user.name }} #}
{{ user->name }}     {# COMPILE ERROR #}

: and the ternary

Whitespace around : is allowed for array-key access:

{{ config:version }}
{{ config : version }}
{{ config: version }}
{{ config :version }}

Because ternaries also use :, a colon inside a branch is an array-key operator only when attached on both sides:

{{ cond ? "yes" : "no" }}   {# ternary #}
{{ cond ? "yes": "no" }}    {# ternary #}
{{ cond ? "yes" :"no" }}    {# ternary #}
{{ cond ? a:b : c }}        {# key read in the branch, then the separator #}

These forms are invalid:

{{ user ? : "fallback" }}   {# WRONG: empty then-branch (PHP's ?: shorthand) #}
{{ user?:nickname }}        {# CORRECT: optional key read #}

Named arguments (name: expr) are parsed before expression compilation and are unaffected.

Nested conditions

Parenthesize nested ternaries:

{{ cond ? (foo ? bar : blubb) : blobb }}
{{ a ? (b ? (c ? d : e) : f) : g }}

A nested ternary in the then-branch may omit parentheses (a ? b ? c : d : e). The else-branch requires them because PHP rejects a ? b : c ? d : e:

{{ a ? b : (c ? d : e) }}   {# CORRECT: parenthesised else-branch #}
{{ a ? b : c ? d : e }}     {# COMPILE ERROR: use the form above #}

For longer if/else chains, use parentheses or {% if %} / {% elseif %}.

Whitespace and line breaks

Whitespace around chain operators is insignificant:

{{ user.
   address.
   city }}

{{ config:
   version }}

. always accesses a property. Use ~ for concatenation:

{{ firstName ~ ' ' ~ lastName }}

An operator without a member (., ->) is a compile error. Optional access must stay attached because a spaced ? begins a ternary: user?:nick reads a key, while user ? x : y is a condition.

${expr} — dynamic variable access

${expr} reads the variable whose name is produced by an expression. $$name is shorthand for ${name}.

{{ ${which} }}                {# the value of the variable named by {{ which }} #}
{{ $$which }}                 {# identical shorthand #}
{{ ${ 'a' ~ 'b' } }}          {# the name may be computed #}
{{ ${ref} ?? 'none' }}        {# absent name: fall back, like {{ name ?? 'x' }} #}
{{ ${which}.title }}          {# chained access applies to the looked-up value #}

${expr} reads from the render scope and loop locals under every policy. An absent name throws unless you provide a ?? fallback. Dynamic names cannot access superglobals or engine internals.

Inside a string literal the $ is literal text: {{ "${which}" }} renders ${which}, not a lookup.

Iteration and container filters

Objects iterate their public properties. The length, keys, values, first, last, and reverse filters accept arrays, Traversable, Countable, or objects with a public toArray(). Stringable value objects without public state retain string semantics; length counts their characters.

Policy-Controlled PHP Access

Policies determine which PHP constructs templates can use; they do not change the template syntax. Registered filters and functions still take precedence. See The Policy API for the available rules and presets.

PHP functions as calls

These require the phpFunctions rule:

{{ strtoupper('ab') }}          {# \strtoupper('ab') #}
{{ implode(',', items) }}       {# \implode(',', $__c_va['items']) #}

PHP functions as filters

With the phpFunctions rule enabled, an unregistered pipe step resolves to a PHP function of the same name, with the piped value as its first argument:

{{ 'ab' |> strtoupper }}              {# \strtoupper($value) #}
{{ 'x' |> str_pad(3, '-') }}          {# \str_pad($value, 3, '-') #}

When the value does not belong first, a single _ placeholder positions it:

{{ 'k' |> array_key_exists(_, m) }}   {# \array_key_exists($value, $m) #}

With phpFunctions enabled, _ may appear once in a PHP-function filter call to choose the piped value's argument position. Elsewhere, _ is an ordinary variable.

Method calls

Method calls require the methodCalls rule. Dot and PHP-style access compile to the same PHP:

{{ user.name() }}                {# static method, dot syntax #}
{{ user?.name() }}               {# nullsafe #}
{{ obj{m}() }}                   {# dynamic method, brace syntax #}

{{ $user->name() }}              {# static method, PHP-style #}
{{ $user?->name() }}             {# nullsafe #}
{{ $user->{$method}() }}         {# dynamic method, PHP-style #}

These calls remain disallowed under every policy:

{{ $fn() }}                      {# ERROR: a call on the root value #}
{{ arr:greet() }}                {# ERROR: a call on a key read, not a member #}

Calls through variables or array values are also rejected.

Raw PHP tags

Raw PHP tags allow trusted templates to use PHP statements and control-structure fragments:

{% php $total = 0; %}
{% php foreach ($items as $item) : %}
    {% php $total += $item['qty']; %}
{% php endforeach %}
{% php echo $total; %}

Split control structures across tags to wrap template markup:

{% php if ($items) : %}
    <ul>
    {% php foreach ($items as $item) : %}
        <li>{{ $item['name'] }}</li>
    {% php endforeach %}
    </ul>
{% php else : %}
    <p>No items.</p>
{% php endif %}

A tag may also contain multiple lines:

{% php
$total = 0;
foreach ($items as $item) { $total += $item['qty']; }
echo $total;
%}

The closing delimiter uses PHP-aware scanning, so %} inside a PHP string does not end the tag.

Function guardrails

When PHP access is allowed, expressions can call PHP functions. Use denyFunctions() to block specific names; it does not restrict calls inside raw {% php %} blocks:

$engine->setPolicy(Policy::unrestricted()->denyFunctions('exec', 'system'));

Changing the list invalidates compiled templates with an outdated policy digest.

Directives

Directives use {% ... %} syntax for control flow and template structure.

Conditional Statements

If / Else / Elseif

{% if user.isActive %}
<span class="badge active">Active</span>
{% elseif user.isPending %}
<span class="badge pending">Pending</span>
{% else %}
<span class="badge inactive">Inactive</span>
{% endif %}

Single condition:

{% if stock > 0 %}
<button>Add to Cart</button>
{% endif %}

Loops

For Loop

Iterate over arrays or objects:

<ul>
  {% for item in items %}
  <li>{{ item.name }} - {{ item.price |> number(2) }}</li>
  {% endfor %}
</ul>

Loop with Key Variable

Use two variables to access both key and value. The first is the key, matching Twig:

{# Indexed array: index, value #}
{% for idx, item in items %}
<li>{{ idx }}: {{ item.name }}</li>
{% endfor %}

{# Associative array: key, value #}
{% for k, v in settings %}
<p>{{ k }}: {{ v }}</p>
{% endfor %}

This compiles to PHP's foreach ($items as $idx => $item).

Range Loops

Inclusive range (includes end):

{% for i in 1..10 %}
  {{ i }} {# Outputs: 1 2 3 4 5 6 7 8 9 10 #}
{% endfor %}

Exclusive range (doesn't include end):

{% for i in 1...10 %}
  {{ i }} {# Outputs: 1 2 3 4 5 6 7 8 9 #}
{% endfor %}

Range with step:

{% for i in 0..100 step 10 %}
  {{ i }} {# Outputs: 0 10 20 30 40 50 60 70 80 90 100 #}
{% endfor %}

Dynamic ranges:

{% for i in start..end step increment %}
  {{ i }}
{% endfor %}

Empty Sequences: {% else %}

An {% else %} branch runs when the sequence is empty:

<ul>
  {% for user in users %}
  <li>{{ user.name }}</li>
  {% else %}
  <li class="empty">No users yet.</li>
  {% endfor %}
</ul>

This works with arrays, mappings, and ranges:

{% for k, v in settings %}{{ k }}={{ v }}{% else %}no settings{% endfor %}

{% for i in 1..0 %}never{% else %}empty range{% endfor %}

Rules:

  • The loop variable is not available in the else branch; a same-named template variable is used instead.
  • A loop accepts one {% else %} and no {% elseif %}.

{% else %} belongs to the innermost open construct at the same nesting level. For example, inside a loop, an {% else %} before {% endif %} belongs to the if; one after {% endif %} belongs to the loop.

Plain {% else %} for Emptiness

Use {% else %} to render fallback content when the loop is empty:

{% for item in items %}{{ item }}{% else %}Nothing to show.{% endfor %}

Leaving a Loop Early: {% break %} and {% continue %}

{% break %} exits a loop; {% continue %} skips to its next iteration:

{% for user in users %}
  {% if user.isBanned %}{% continue %}{% endif %}
  {% if user.isOwner %}{% break %}{% endif %}
  <li>{{ user.name }}</li>
{% endfor %}

Numeric levels follow PHP: enclosing loops and {% switch %} blocks count; if blocks do not. Without a level, {% break %} exits the innermost loop or switch.

Inside a switch, {% break %} exits only the switch; use {% break 2 %} to exit the switch and its enclosing loop.

{% for row in rows %}
  {% switch row.type %}
    {% case "stop" %}{% break 2 %}   {# leaves the switch AND the loop #}
    {% case "skip" %}{% break %}     {# leaves only the switch         #}
    {% default %}{{ row.label }}
  {% endswitch %}
{% endfor %}

Levels also target outer loops:

{% for row in rows %}
  {% for cell in row %}
    {% if cell.isEmpty %}{% break 2 %}{% endif %}  {# abandon the whole table #}
  {% endfor %}
{% endfor %}

Levels are validated at compile time. They must be integer literals; expressions, variables, floats, and values deeper than the open constructs are rejected:

{% for row in rows %}{% break 5 %}{% endfor %}
{# COMPILE ERROR: '{% break 5 %}' reaches past the 1 enclosing loop or switch #}

{% continue %} must target a loop, not a switch. Clarity rejects levels that would make PHP treat continue as break.

A loop's {% else %} branch is outside the loop, so {% break %} there is a compile error.

Use . for object properties and : for map keys (row:type); see Variable Access.

Macros

Macros are reusable template fragments defined and called within a template.

Defining a Macro

{% macro card(title, body) %}
<div class="card">
  <h3>{{ title }}</h3>
  <p>{{ body }}</p>
</div>
{% endmacro %}

Calling a Macro

Use {% call macroName(arg1, arg2) %} to invoke a macro:

{% call card("Welcome", "Hello from Clarity!") %}
{% call card(article.title, article.excerpt) %}

Default Parameter Values

Parameters may have default values; optional parameters must come last:

{% macro terminal(label, command, icon = "fa-solid fa-terminal") %}
  <i class="{{ icon }}"></i> <span>{{ label }}</span>
  <pre><code>{{ command }}</code></pre>
{% endmacro %}

{% call terminal("Install", "composer require x") %}           {# default icon #}
{% call terminal("Install", "composer require x", "fa-bolt") %} {# own icon #}

Defaults are expressions compiled at the call site. They can use caller variables and earlier parameters, including filters and function calls:

{% macro badge(text = "new" |> upper) %}[{{ text }}]{% endmacro %}
{% macro row(label = slice("abcdef", 0, 3)) %}{{ label }}{% endmacro %}
{% macro titled(a, b = a ~ "!") %}{{ a }}{{ b }}{% endmacro %}  {# b reads a #}

Named Arguments

Named arguments (name: expr) bind parameters by name, allowing calls to skip optional parameters:

{% macro terminal(label, command, icon = "fa-terminal", language = "") %}
  <i class="{{ icon }}"></i> <span>{{ label }}</span>
  <pre><code class="{{ language }}">{{ command }}</code></pre>
{% endmacro %}

{# icon keeps its default; language is set by name #}
{% call terminal("Install", "composer require x", language: "bash") %}

Argument rules:

  • Positional arguments must come before named ones, and each name must be unique. {% call t(a: 1, 2) %} and {% call t(a: 1, a: 2) %} both fail.
  • Names must match macro parameters; unknown names are errors.
  • One parameter cannot be filled both ways. {% call t(1, a: 2) %} fails when a is the first parameter, but is fine when a is the second.
  • Arguments are expressions. Parenthesize colon-key reads to distinguish them from named arguments: {% call t((user:name)) %}.

Named arguments work the same way on filters and functions (Filters and Functions).

Caller Bodies: {% call %}…{% endcall %} and {% caller %}

A call may supply a body that the macro renders at each {% caller %} directive:

{% macro card(title) %}
<section class="card">
  <h2>{{ title }}</h2>
  {% caller %}
</section>
{% endmacro %}

{% call card("Welcome") %}
  <p>Anything here is the caller's.</p>
{% endcall %}

{% caller %} is a directive, not a function. Its source body is compiled at the caller site and may render zero or more times:

{% set x = caller() %}     {# ERROR: 'caller' is not a function #}
{{ caller() ~ "!" }}       {# ERROR: same #}

Rules:

  • It takes no arguments; the body can access caller variables and macro parameters.
  • If the macro has no {% caller %}, the body is not rendered. Multiple directives render it multiple times.
  • Nested caller bodies resolve to their own call.
  • {% call name() %} without a body remains a plain macro call.
  • caller cannot be used as a macro name.

Macro Rules

  • Definitions render nothing; calls expand at their call site during compilation.
  • Macro names are identifiers, so they are case-sensitive and may not be a directive keyword (if, for, set, block, include, …).
  • Recursive calls fail compilation.
  • A macro becomes available after its definition or static include. Independently rendered templates do not share macros.
  • Define macros at the top level, not inside another macro. Names are not scoped.

Note: {% parent %} and {% caller %} are directives, not macros. Both inline text that is only known at compile time — a parent block's content and a call site's body respectively — so neither is defined with {% macro %}, and neither is an expression.

Note: Macros used to be defined as {% macro @name %} and called as {% @name(args) %}, and {% parent %} used to accept an {% @parent %} spelling. Those forms are removed. A {% macro @name %} is refused with a message naming the replacement; an {% @name(args) %} or {% @parent %} tag is simply an unknown directive.

Multi-Parameter Example

{% macro avatar(name, size, href) %}
<a href="{{ href }}" class="avatar avatar--{{ size }}">
  <span>{{ name |> upper |> slice(0, 2) }}</span>
</a>
{% endmacro %}

{% for user in team %}
  {% call avatar(user.name, "md", "/users/" ~ user.id) %}
{% endfor %}

Variable Assignment

Set variables for reuse:

{% set total = items.length %}
{% set fullName = user.firstName ~ ' ' ~ user.lastName %}
{% set discount = price * 0.1 %}

<p>Total items: {{ total }}</p>
<p>Customer: {{ fullName }}</p>
<p>You save: {{ discount |> number(2) }}</p>

Assigned names live in the render's single scope, so they stay visible for the rest of the template — including after an {% if %}, a {% for %}, a {% block %} or an {% include %}. A name assigned inside a loop keeps its last value and is not cleared when the loop ends; the loop variable itself is, because it is bound to a PHP local rather than to the scope.

There is no {% with %} block to open a nested scope; see Deliberate Differences.

Template Inheritance

Extends

Extend a parent template:

{% extends "layouts/main" %}

This must be the first directive, before any output.

Blocks

Define sections that child templates can override:

Parent template (layouts/main.clarity.html):

<!DOCTYPE html>
<html>
  <head>
    <title>{% block title %}Default Title{% endblock %}</title>
    {% block head %}{% endblock %}
  </head>
  <body>
    <header>
      {% block header %}
      <h1>My Site</h1>
      {% endblock %}
    </header>

    <main>{% block content %}{% endblock %}</main>

    <footer>
      {% block footer %}
      <p>&copy; 2026</p>
      {% endblock %}
    </footer>
  </body>
</html>

Child template (pages/about.clarity.html):

{% extends "layouts/main" %}

{% block title %}About Us{% endblock %}
{% block content %}
  <h2>About Our Company</h2>
  <p>We are awesome!</p>
{% endblock %}

Unchanged blocks use the parent's default content.

Parent Block Fallback

Use {% parent %} inside an overriding child block to insert the parent's content:

{% extends "layouts/main" %}

{% block title %}
  Admin | {% parent %}
{% endblock %}

If the parent block contains My Website, this renders Admin | My Website.

{% parent %}:

  • Is valid only in an overriding child block.
  • Resolves at compile time and may appear multiple times.
  • Refers to the immediate parent in multi-level inheritance.

Includes

Static Include

Include another template, sharing the current variable scope:

{% include "partials/header" %}

<main>
  <!-- page content -->
</main>

{% include "partials/footer" %}

Static includes are inlined at compile time.

Static includes can provide macros; include the macro library before calling its macros.

Include with Namespaces

{% include "admin::sidebar" %}
{% include "emails::header" %}

See Advanced Topics for namespace configuration.

Operators

Comparison Operators

{% if age >= 18 %}
{% if status == 'active' %}
{% if count != 0 %}
{% if price < 100 %}
{% if score > 50 %}
{% if rating <= 5 %}
Operator Description
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

Logical Operators

{% if user.isActive and user.role == 'admin' %}
{% if status == 'pending' or status == 'review' %}
{% if not user.isBlocked %}
Operator Description
and Logical AND
or Logical OR
not Logical NOT

Note: The symbols &&, ||, and ! are also accepted (they pass straight through to PHP).

Tests

Tests use word-based syntax and registered callables, so they work under every policy. Use them wherever a boolean expression is accepted.

{# membership — value in a list, substring in a string, key in a mapping #}
{% if 2 in [1, 2, 3] %}…{% endif %}
{% if 'ell' in word %}…{% endif %}
{% if role in user:roles %}…{% endif %}
{% if x not in items %}…{% endif %}

{# string tests #}
{% if name starts with 'Jo' %}…{% endif %}
{% if name ends with 'hn' %}…{% endif %}
{% if name matches '/^J.*n$/' %}…{% endif %}

{# numeric / identity tests #}
{% if n is even %}…{% endif %}
{% if n is odd %}…{% endif %}
{% if n divisible by 3 %}…{% endif %}
{% if a is same as(b) %}…{% endif %}
{% if value is iterable %}…{% endif %}

These tests do not read their operand, so they are safe for names not passed to the template:

{% if name is defined %}…{% endif %}
{% if name is not defined %}…{% endif %}
{% if nickname is null %}…{% endif %}
{% if items is empty %}…{% endif %}
{% if items is not empty %}…{% endif %}

nil is an alias for null, including in tests: {{ nil }}, {{ x is nil }}, {{ x ?? nil }} and {{ f(nil) }} all work.

is defined is equivalent to PHP's isset(): absent and null values are both undefined. Use is null to test the value:

user user is defined user is null
absent false true
null false true
'x', 0 true false

Tests compose with logical operators, ternaries, and filters:

{% if role in user:roles and user is not null %}…{% endif %}
{{ 2 in [1, 2] ? 'yes' : 'no' }}
{{ (name |> lower) is defined ? 'set' : 'unset' }}

The tests starts with, ends with, divisible by and same as are two words. An unrecognised word after is (x is frobnicated) is a compile error.

Bitwise Operators

Use the keyword forms to avoid conflict with the | filter-pipe operator:

{{ flags bor mask }}    {# bitwise OR  — flags | mask  #}
{{ flags band mask }}   {# bitwise AND — flags & mask  #}
{{ flags bxor mask }}   {# bitwise XOR — flags ^ mask  #}
{{ bnot flags }}        {# bitwise NOT — ~flags        #}
{{ flags blsh 2 }}      {# bitwise left shift — flags << 2  #}
{{ flags brsh 2 }}      {# bitwise right shift — flags >> 2  #}
Operator PHP equivalent Description
bor | Bitwise OR
band & Bitwise AND
bxor ^ Bitwise XOR
bnot ~ Bitwise NOT
blsh << Bitwise left shift
brsh >> Bitwise right shift

Arithmetic Operators

{% set total = price + tax %}
{% set discount = price * 0.1 %}
{% set remaining = total - paid %}
{% set perItem = total / count %}
{% set remainder = total % 10 %}
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo

String Concatenation

Use the ~ operator:

{% set fullName = firstName ~ ' ' ~ lastName %}
{% set greeting = 'Hello, ' ~ user.name ~ '!' %}

<p>{{ 'Total: ' ~ total ~ ' items' }}</p>

Filter Pipe Operator

Both | and |> pipe a value through a filter. They are fully interchangeable:

{{ name | upper }}         {# Twig / Svelte style #}
{{ name |> upper }}        {# Clarity fat-pipe style #}

Whenever you need bitwise OR, use the bor keyword instead of | (see Bitwise Operators above).

|| (double pipe) is always logical OR and is never treated as a filter pipe.

Ternary Operator

{{ user.isActive ? 'Active' : 'Inactive' }}
{{ stock > 0 ? 'In Stock' : 'Out of Stock' }}
{{ age >= 18 ? 'Adult' : 'Minor' }}

Syntax: condition ? valueIfTrue : valueIfFalse

Conditions nest, but a nested ternary in the else-branch must be parenthesised — PHP rejects a ? b : c ? d : e outright. See Nested conditions.

{{ cond ? (foo ? bar : blubb) : blobb }}

Null Coalescing

{{ user.nickname ?? user.name }}
{{ customTitle ?? defaultTitle }}

Returns the right value if the left is null or undefined.

Expressions

Literal Values

{{ 42 }}
{{ 3.14 }}
{{ true }}
{{ false }}
{{ null }}
{{ "string literal" }}
{{ 'single quotes' }}

Cast Syntax

A PHP-style cast prefix converts a value's type. It is equivalent to the cast filters:

{{ (int) x }}                    {# same as {{ x |> int }}        #}
{{ (float) '3.7' }}              {# 3.7                           #}
{{ (string) 1.5 }}               {# '1.5'                         #}
{{ (bool) value }}               {# true or false                 #}
{{ (array) value }}              {# [value]                       #}
{{ (object) value }}             {# scalar 1 becomes {"scalar":1} #}

The available types are int, float, string, bool, array and object. object converts a scalar or an array into an object.

The operand may be a name, chain, index, literal, parenthesized expression, or another cast:

{{ (int) (float) x }}            {# 3.9 -> 3 #}

A cast can be followed by a pipe:

{{ (int) x |> string }}          {# cast, then filter #}

Cast or parenthesized expression

The parser distinguishes casts from parenthesized expressions by the token after the closing parenthesis. A cast type followed by an operand is a cast; whitespace is optional.

Expression Reading
(int) x cast: whitespace, then a name
(int)x cast: same reading without whitespace
(int) -5 cast: whitespace, then a sign
(int)-5 cast: sign directly before a number
(int) (x) cast of the grouped x
(int)(x) cast of the grouped x, not a call
(int)[0] cast of the array [0], not an index
(a) + b not a cast: + cannot start an operand
(a) ? b : c not a cast: ? cannot start an operand
(a) x not a cast: existing reading is unchanged

Operands can begin with an identifier, $, quote, digit, (, [, {, or a sign directly before a number. Other parenthesized expressions keep their existing meaning. Names that are not cast types are never treated as casts.

- is a sign only when immediately followed by a digit or .; thus (int) -5 is a cast, while (a) - 5 is subtraction.

Collection Literals

Arrays (lists — [] always holds values):

{% set numbers = [1, 2, 3, 4, 5] %}
{% set mixed = [true, "text", 42, user.name] %}

Maps (associative arrays — {} is a PHP array, read with : or [...]):

{% set person = { name: "John", age: 30, active: true } %}
{% set data = { id: item.id, title: item.title } %}

{{ person:name }} {{ person["age"] }}

A brace literal is an array, not an object. Reading person.name from the map above raises Cannot read property "name" on array; see Variable Access.

Object literals — prefix the literal with the object cast. Inside it, a nested brace literal is another object literal, at any depth:

{% set person = (object) { name: "John", address: { city: "Rome" } } %}

{{ person.name }}            {# John                                    #}
{{ person.address.city }}    {# Rome — no cast needed at the nested level #}

The cast also applies to nested brace literals. An uncast brace literal remains a map:

Spelling Meaning
(object) { a: { b: 1 } } object, with a an object
{ a: { b: 1 } } map, with a a map — unchanged
{ a: { b: 1 } } |> object PHP's shallow cast: a stays a map
(object) { a: flag ? {b:1} : {} } a is a map: the literal is not the whole value

An array element is always a value, even inside an object literal:

{% set u = (object) { tags: ["a", "b"] } %}
{{ u.tags[1] }}              {# b #}

{} must stay an array: include("x", { title: "Hi" }), spread, merge, reverse and {% set x:key = … %} all require one. Reach for (object) only when . is what you want to write.

Spread operator in collections:

{% set extended = [1, 2, ...moreNumbers, 99] %}
{% set merged = { foo: "bar", ...otherData } %}

Built-in Functions

vars()

Returns the current template variables:

{% set allVars = vars() %} {{ allVars |> json }}

include()

Dynamically render another template at runtime:

{{ include("partials/card", { title: "Hello", ...vars() }) }}
{{ include(templateName, variables) }}

Unlike {% include %}, this function:

  • Renders at runtime and accepts dynamic template names.
  • Returns rendered markup and accepts custom context variables.

Example:

{% for componentType in components %}
{{ include("components/" ~ componentType, { data: item }) }}
{% endfor %}

See Filters and Functions for custom functions.

Comments

Comments are stripped during compilation and never rendered:

{# This is a comment #}
{# Multi-line comment
   Useful for documentation #}
{# TODO: Add pagination here #}

Context Hints

@context annotations set the escaping mode for following expressions. Clarity also detects <script> and <style> contexts; use an annotation to override it:

{# @context js #}
  var userData = '{{ user |> json }}';                        {# escaped string content …
                                                                 the quotes come from you #}
  var config   = JSON.parse('{{ config |> json |> raw }}');   {# valid JSON as an object #}
{# @context html #}
  <p>{{ message }}</p>                 {# Back to standard HTML escaping #}

Available contexts:

Context Output escaping
html htmlspecialchars() (default)
js Quoted tags emit escaped string content; unquoted tags emit a JSON literal.
css Cast to (string); no HTML escaping.

Clarity detects <script> and <style> tags. Use {# @context … #} when that detection is insufficient, such as inside a string containing tag-like text.

Inside <script>: two forms, chosen by the position

In <script>, interpolation output depends on whether the tag is quoted:

<script>
var name = "{{ user.name }}";   {# -> var name = "Ada";          string content #}
var obj  = {{ user }};          {# -> var obj  = {"name":"Ada"};  JSON literal   #}
</script>

Quoted: quotes are part of the template; the value is escaped string content.

<script>
var id   = '{{ user.id }}';     {# -> var id   = '7';     #}
var text = "hi {{ user.name }}";{# -> var text = "hi Ada"; #}
</script>

Unquoted: the value is emitted as a JSON literal, preserving strings, numbers, booleans, and arrays:

<script>
var seats  = {{ license.seats }};    {# -> var seats  = 3;          #}
var paid   = {{ order.paid }};       {# -> var paid   = true;       #}
var tiers  = {{ tiers }};            {# -> var tiers  = [1,2,3];    #}
var config = {{ config }};           {# -> var config = {"a":1};    #}
</script>

This avoids conversions such as Number(…), === '1', and JSON.parse(…). JSON.parse('{{ x |> json |> raw }}') remains available.

Classification behavior

Clarity classifies each tag as quoted string content or an unquoted JSON value. Misclassification can change the result or produce invalid JavaScript:

Misjudgement Output Result
quoted tag read as code var x = {{ v }}; → var x = "Ada"; inside your "…" ""Ada"" — JS syntax error
code tag read as string var x = {{ n }}; → var x = 3; inside a string position escaped content, still a valid literal
a number, either way 3 and the content of 3 are both 3 identical, by design

Tests across 72 combinations of both forms and hostile values (quotes, backticks, ${…}, </script>, newlines, NUL bytes, BOM, and emoji) produced valid JavaScript; no value containing ;alert(1) became code, including with preceding comments, regular expressions, and template literals.

Positions that are rejected

Tags inside regular expressions or template-literal text have no valid output form and cause a compile error:

<script>
var r = /{{ v }}/;      {# ClarityException — not meaningful in a pattern #}
var t = `{{ v }}`;      {# ClarityException — use "{{ v }}" or ${ {{ v }} } #}
var ok = `${ {{ v }} }`;{# fine: back inside JavaScript, so JSON literal #}
</script>

raw remains unescaped in every context. For example, {{ x |> json |> raw }} is emitted unchanged.

What the scan understands

The scanner recognizes JavaScript comments, regular expressions, and template literals, so quotes inside them are not treated as delimiters:

<script>
// don't touch this: "{{ value }}"      {# apostrophe in a line comment #}
var t = `it's`; var a = "{{ value }}"; {# apostrophe in backticks #}
var re = /"/; var a = "{{ value }}";   {# quote in a regex literal #}
var d = a / 2; var s = "{{ value }}";  {# division, not a regex #}
</script>

Known limitations:

  • `{{ value }}` — a tag in template-literal text is rejected (see above);
  • a comment opener split across text segments (a / ending one segment and * starting the next). Moving the expression avoids this case.

In ambiguous cases, the scanner may reject a valid template rather than choose an unsafe output form.

Complex Examples

Nested Loops

<table>
  {% for category in categories %}
  <tr>
    <th>{{ category.name }}</th>
    <td>
      <ul>
        {% for product in category.products %}
        <li>{{ product.name }} - {{ product.price |> number(2) }}</li>
        {% endfor %}
      </ul>
    </td>
  </tr>
  {% endfor %}
</table>

Conditional Rendering with Loops

{% if users.length > 0 %}
  <ul>
    {% for user in users %} {% if user.isActive %}
    <li class="active">{{ user.name }}</li>
    {% endif %} {% endfor %}
  </ul>
{% else %}
  <p>No active users found.</p>
{% endif %}

Complex Variable Assignment

A brace literal is a map, so it is read with :. Prefix it with (object) when the dotted spelling reads better:

{% set userData = (object) {
  fullName: user.firstName ~ ' ' ~ user.lastName,
  age: user.birthYear ? (2026 - user.birthYear) : null,
  isAdult: user.birthYear and (2026 - user.birthYear) >= 18
} %}

<p>Name: {{ userData.fullName }}</p>
{% if userData.isAdult %}
  <p>Age: {{ userData.age }}</p>
{% endif %}

Without the cast, the same literal is a map and userData.fullName is an error (Cannot read property "fullName" on array); userData:fullName is the read.

Dynamic Includes

{% for widget in dashboard.widgets %}
  {{ include("widgets/" ~ widget.type, {
    title: widget.title, data: widget.data, config: widget.config }) }}
{% endfor %}

Next Steps

Quick Reference

Directive Summary

Directive Purpose
{% if condition %} Conditional rendering
{% elseif condition %} Alternative condition
{% else %} Fallback case
{% endif %} End conditional
{% for item in array %} Loop over a sequence
{% for key, value in array %} Loop with key variable
{% for i in start..end %} Range loop (inclusive end)
{% for i in start...end %} Range loop (exclusive end)
{% for x in list if cond %} Loop, filtering per iteration
{% else %} (inside a loop) Runs when the loop is empty
{% elsefor %} The same, unambiguously
{% break %} / {% continue %} Leave / skip an iteration
{% break 2 %} / {% continue 2 %} Leave / skip N levels (PHP's rule)
{% endfor %} End loop
{% switch expr %} … {% endswitch %} Multi-way branch
{% case expr %} / {% default %} Switch labels
{% autoescape false %} … {% endautoescape %} Set a block's autoescape mode
{% verbatim %} … {% endverbatim %} Literal text, tags included
{% do expr %} Evaluate, print nothing
{% set variable = value %} Variable assignment
{% set a = 1, b = 2 %} Several assignments
{% set n += 1 %} Compound assignment
{% extends "template" %} Inherit from layout
{% block name %}...{% endblock %} Define/override block
{% include "template" %} Include another template
{% macro name(params) %}...{% endmacro %} Define a reusable macro
{% call name(args) %} Call a macro
{% call name(a, b: value) %} Call a macro with a named argument (skips middle optionals)
{% call name() %}…{% endcall %} Call with a {% caller %} body
{% macro name(a, b = value) %} Macro with a default value
{% caller %} Inline the call-site body
{% parent %} Inline parent block content
{# comment #} Template comment
{# @context js|css|html #} Switch escaping context

Operator Summary

Category Operators
Comparison == != < > <= >=
Logical and or not
Tests in not in is defined is null is empty is iterable
is even is odd starts with ends with matches
divisible by same as
Type tests is numeric is scalar is string is integer is float
is boolean is array is object is callable
Arithmetic + - * / % **
Bitwise band bor bxor bnot blsh brsh & ^ ~ << >>
String ~ (concatenation)
Ternary condition ? true : false
Null coalesce ??
Spread ... (in arrays/objects)