Documentation

Advanced Topics

This guide covers advanced Clarity features including template loaders, caching, auto-escaping, error handling, and Unicode support.

Template Loaders

Clarity resolves template names through a pluggable loader system. The default FileLoader handles straightforward file-based resolution. Two additional loaders cover more advanced scenarios.

Namespaces

Use addNamespace() to map a short alias to a template directory. Reference templates with namespace::path.

// Register namespaces individually
$engine
    ->addNamespace('admin',      __DIR__ . '/views/admin')
    ->addNamespace('emails',     __DIR__ . '/views/emails')
    ->addNamespace('components', __DIR__ . '/views/components');

// Or pass them all at once in the constructor
$engine = new ClarityEngine([
    'viewPath'   => __DIR__ . '/views',
    'namespaces' => [
        'admin'      => __DIR__ . '/views/admin',
        'emails'     => __DIR__ . '/views/emails',
        'components' => __DIR__ . '/views/components',
    ],
]);

Use the namespace prefix inside templates:

{% include "admin::partials/sidebar" %}
{% extends "emails::layouts/base" %}
{{ include("components::card", { title: item:title }) }}
{# Unprefixed names resolve against the base viewPath: #}
{% extends "layouts/main" %}

addNamespace() sets up a DomainRouterLoader with the base viewPath as the fallback, so unprefixed template names continue to work.

To inspect registered namespaces at runtime:

$map = $engine->getNamespaces(); // ['admin' => '/path/to/views/admin', ...]

DomainRouterLoader

DomainRouterLoader dispatches template resolution based on a domain::localName prefix. Namespaces use this mechanism under the hood, mapping each namespace to a corresponding domain.

use Clarity\Template\DomainRouterLoader;
use Clarity\Template\FileLoader;

$engine->setLoader(new DomainRouterLoader(
    [
        'admin'      => new FileLoader(__DIR__ . '/views/admin'),
        'emails'     => new FileLoader(__DIR__ . '/views/emails'),
        'components' => new FileLoader(__DIR__ . '/views/components'),
    ],
    fallback: new FileLoader(__DIR__ . '/views'),  // handles names without a prefix
));

Templates are referenced using the domain::path syntax:

{% include "admin::sidebar" %}
{% extends "admin::layouts/base" %}
{{ include("emails::welcome", { userName: user:name }) }}

Dots and slashes are interchangeable as path separators within the local name:

{% include "admin::partials.sidebar" %}
{% include "admin::partials/sidebar" %}
{# Both are equivalent #}

If no :: prefix is present and a fallback loader is configured, the name is passed to the fallback unchanged.

Example Structure

views/
├── layouts/
│   └── main.clarity.html           (fallback)
├── pages/
│   ├── home.clarity.html           (fallback)
│   ├── about.clarity.html          (fallback)
│   └── users/
│       └── list.clarity.html       (fallback)
├── admin/                          (domain: admin)
│   ├── layouts/
│   │   └── admin.clarity.html
│   └── pages/
│       └── users.clarity.html
├── components/                     (domain: components)
│   ├── buttons/
│   │   └── primary.clarity.html
│   └── cards/
│       └── user-card.clarity.html
└── emails/                         (domain: emails)
    └── welcome.clarity.html

CompositeLoader

CompositeLoader chains multiple loaders and returns the first successful result. It is useful for overlaying a dynamic source (e.g. database or array) on top of a file-based one:

use Clarity\Template\CompositeLoader;
use Clarity\Template\ArrayLoader;
use Clarity\Template\FileLoader;

$engine->setLoader(new CompositeLoader(
    new ArrayLoader(['promo' => '<p>{{ offer }}</p>']),  // checked first
    new FileLoader(__DIR__ . '/views'),                   // fallback
));

The loaders are tried in the order they are passed to the constructor. The first loader that returns a successful result wins.

setExtension() and Loaders

When setExtension() is called on the engine it automatically propagates to all FileLoader instances inside any composite or domain-router loader:

$engine->setExtension('.tpl.html');  // applies to every nested FileLoader

Caching

Clarity compiles .clarity.html templates into PHP classes and caches them on disk.

How Caching Works

  1. First render: the template is compiled to PHP and written to the cache directory
  2. Subsequent renders: the compiled body is loaded directly (one require, accelerated by OPcache)

Content-Addressed Bodies

Each template uses a serialized pointer to its current compiled body:

cache/clarity/a1/
├── a1b2c3d4…cdef.ptr                 pointer
├── a1b2c3d4…cdef-9f8e7d6c5b4a.php   compiled body (class)
└── a1b2c3d4…cdef-112233445566.php   superseded body

Bodies are named by a digest of their emitted source and are never rewritten. Unchanged recompiles reuse the body; changed source writes a new body and updates the pointer. Pointer files are rewritten only when their contents change.

This layout avoids invalidating shared OPcache entries. Generated bodies are backdated past opcache.file_update_protection and are written without opcache_invalidate(). In testing with OPcache enabled, 300 identical recompiles and 20 content changes produced 0 B of shared-memory waste.

The pointer is needed because a body's content-addressed path is known only after compilation. It records the current body for other workers without loading candidate classes. Its .ptr file stores serialized data, read with file_get_contents() and unserialize(..., ['allowed_classes' => false]). The body path is derived from the template and class hashes, so moving the cache directory does not invalidate it. Cache::templateHash() uses xxh128 for the template-name hash used in the pointer path, body path and class name.

Serialization also supports non-UTF-8 data. For a 12-dependency pointer, reading and decoding took 39.3 µs with serialize() versus 47.0 µs with JSON.

Pointer cache (APCu)

The .ptr file remains the durable record. A pointer cache only fronts reads, so a restart, a clearCache(), or a host without APCu degrades to slower — never to wrong.

$engine->useApcuPointerCache();     // returns bool: false if APCu is unusable here

Under FPM every worker shares one APCu segment, so a pointer any worker has already read is available to all of them. That is the case worth optimising: a cold request drops from a file_get_contents() + unserialize() to an apcu_fetch() (measured: 166 µs → 46 µs per render). A long-lived worker gains nothing, because it answers from its own in-process registry (~27 µs) and never reaches either store.

useApcuPointerCache() returns whether APCu is actually usable and hasPointerCache() reports the same thing, so a host where the extension is missing or apc.enable_cli is off says so instead of silently doing nothing.

Any backend can be injected with setPointerCache() — it only needs get(), put(), forget() and isAvailable():

$engine->setPointerCache(new MyPointerCache());   // null = read from disk only

Superseded bodies can be removed with:

php azera cache:prune
php azera cache:prune --older-than=3600

cache:status reports how many unreferenced bodies exist.

Long-Lived Workers

PHP caches file metadata and realpaths per process. Long-lived workers can therefore observe stale template mtimes after files change or a deployment swaps a symlink. FileLoader::load() calls clearstatcache(true, $path) before reading the mtime, clearing both caches so the revision reflects the current file.

Each dependency adds a real stat() to a warm render — about 16 µs on Windows and less on Linux in the measured setup. Set revalidateFreq to reuse a positive freshness verdict for N seconds when delayed propagation is acceptable:

$engine->setRevalidateFreq(2);   // at most 2 s of staleness

Compiler Version

Each compiled class records the compiler version. The loader recompiles cached files when their version is stale or missing.

The compiled class also records the debug-mode flag and a digest of the policy it was built under; a change to either recompiles the template.

The class name itself ends in a digest of the emitted source (__Clarity_<hash(template)>_<digest>), which is what makes the body content-addressed and lets an unchanged recompile reuse the file already on disk.

Cache Configuration

$engine->setCachePath(__DIR__ . '/cache/clarity'); // must be writable by the web server
$cachePath = $engine->getCachePath();              // default: sys_get_temp_dir() . '/clarity'

$engine->flushCache();  // delete every cached file, bodies included
$engine->pruneCache();  // delete only unreferenced bodies

Cache Directory Structure

Cached files are organized by hash:

cache/clarity/
├── a1/a1b2c3d4…cdef.ptr              pointer  (views/home.clarity.html)
├── a1/a1b2c3d4…cdef-9f8e7d6c5b4a.php body     (current)
├── b1/b2c3d4e5…a1b2.ptr              pointer  (layouts/main.clarity.html)
└── ...

Pointer names are deterministic hashes of the template name; body names append the content digest.

Auto-Escaping

Clarity automatically escapes all output for security by default.

How Auto-Escaping Works

Expressions are wrapped with htmlspecialchars() to prevent XSS attacks:

{{ userInput }}
<!-- If userInput = "<script>alert('XSS')</script>" -->
<!-- Output: &lt;script&gt;alert('XSS')&lt;/script&gt; — safe, displayed as text -->
htmlspecialchars($vars['userInput'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')

Disabling Auto-Escaping (raw filter)

To output raw HTML, use the raw filter. It is a compile-time marker that disables the auto-escape wrapper, and it applies to the entire expression when it appears anywhere in the filter chain. Its opposite is escape, which applies the escaping itself and cancels the wrapper:

{{ article:sanitizedBody |> raw }}          {# sanitized HTML from a WYSIWYG editor #}
{{ renderedWidget |> raw }}                 {# pre-rendered HTML from your application #}
{{ data |> json |> raw }}                   {# JSON output #}
{{ description |> nl2br |> raw }}           {# HTML-generating filters like nl2br #}
{{ description |> trim |> nl2br |> raw }}   {# raw anywhere disables escaping for the whole chain #}

Only use raw with trusted content — never with user input.

raw and escape are the two halves of one switch. Both cancel the automatic wrapper; escape performs its work itself, so the value is escaped exactly once:

Output Emitted
{{ x }} htmlspecialchars((string)(x))
{{ x |> escape }} htmlspecialchars((string)(x)) — the same
{{ x |> raw }} x, verbatim

Safe HTML Generation

If you need to generate HTML in a filter, escape the dynamic content internally so the returned HTML is safe:

$engine->addFilter('badge', function($value, string $type = 'default') {
    $safeValue = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    return "<span class=\"badge badge-$type\">$safeValue</span>";
});
{{ status |> badge('success') |> raw }}

Error Handling

Clarity provides detailed error messages with template file and line mapping.

ClarityException

All template errors throw Clarity\ClarityException:

use Clarity\ClarityException;

try {
    $output = $engine->render('page', $data);
} catch (ClarityException $e) {
    echo "Template error: " . $e->getMessage();
    echo "\nTemplate: " . $e->templateName;   // logical: "pages/home"
    echo "\nPath:     " . $e->templatePath;   // physical, or "" for a non-file loader
    echo "\nLine:     " . $e->templateLine;
}

templateName is the requested name (for example, pages/home), and templatePath is the resolved file path. It is empty for loaders without a filesystem path. Custom loaders can return a path in TemplateSource.

ClarityException exposes the template location through templateName and templateLine, and mirrors it to getFile() and getLine(). This lets uncaught errors point to the template source:

Fatal error: Uncaught Clarity\ClarityException: '{% php %}' is not allowed by this policy.  
Grant the 'rawPhp' rule to allow it. in pages/home on line 4 in
/srv/app/views/pages/home.clarity.html on line 4

getFile() prefers the physical path, then the logical name, and falls back to the engine frame if no template location is available. The exception message keeps the logical name, and getTrace() retains the PHP call stack.

The original throwable is available as $e->getPrevious().

What gets mapped

Failure Result
Undefined variable / array key / null offset ClarityException — the render is aborted
Syntax error in a template expression ClarityException wrapping the ParseError, pointing at the template line
Exception thrown by a filter, function, or inline-filter PHP ClarityException wrapping the original, pointing at the template line that invoked it
TypeError / Error (e.g. a typed filter argument rejects the value) ClarityException wrapping the original, pointing at the template line
Other PHP diagnostics (e.g. foreach() over null, or a deprecation) Handed to your own error handler, annotated … in <template>:<line>; rendering continues and the partial output is returned
Exception raised entirely outside the render path Passed through unchanged, keeping its original type

Interoperating with your own error handler

Clarity installs an error handler for the duration of a render and chains to whatever handler was already installed, so your logging / error-reporting listener keeps working:

set_error_handler(function (int $no, string $msg, string $file, int $line): bool {
    $log->warning($msg, ['file' => $file, 'line' => $line]);
    return true;
});

// Diagnostics raised inside a template arrive here annotated with the template
// location, e.g. "foreach() argument must be of type array|object, null given
// in pages/list on line 4".  $file and $line are the TEMPLATE's file and line.
$engine->render('pages/list', $data);

These details have three implications:

  • Clarity does not set a severity policy. Forwarded diagnostics can be logged, ignored, or converted to exceptions by the configured handler. Clarity itself does not log, suppress, or throw them. If the handler converts warnings to exceptions, a template warning will stop the render.
  • The E_USER_* level is a translation, not a 1:1 mapping. A handler invoked from PHP's own machinery may receive only a user-level constant, while the level still indicates the diagnostic kind: a notice arrives as E_USER_NOTICE, a deprecation as E_USER_DEPRECATED, and a native E_WARNING such as an undefined variable arrives as E_USER_WARNING. A handler that converts warnings to exceptions will not stop the render for a notice.
  • Diagnostics raised outside the template are passed to the handler without template-location annotations.

Error Messages

Clarity maps errors back to the original template file and line, even though the error occurs in compiled PHP:

Syntax error in template: unexpected token '}' in views/products/show.clarity.html on line 42

For a catalogue of common errors and their fixes, see the Troubleshooting Guide.

Unicode Support

Clarity is fully Unicode-aware via the mbstring extension.

Built-in Unicode Support

String filters use multibyte functions:

{{ "Ä Ö Ü ß" |> upper }} {# Output: "Ä Ö Ü SS" (Unicode-aware) #}
{{ "ПРИВЕТМИР" |> lower }} {# Output: "привет мир" #}
{{ "你好世界" |> length }} {# Output: 4 (characters, not bytes) #}

Emoji Support

Clarity handles emoji correctly:

{{ "Hello 👋 World 🌍" |> length }} {# Output: 13 (counts emoji as 1 character each) #}
{{ "🚀🌟💡" |> reverse }} {# Output: "💡🌟🚀" #}

Character Encoding

Clarity assumes UTF-8 encoding:

  • All templates should be saved as UTF-8
  • Input data should be UTF-8
  • Output is UTF-8

If working with other encodings:

// Convert to UTF-8 before rendering
$data['text'] = mb_convert_encoding($data['text'], 'UTF-8', 'ISO-8859-1');

$engine->render('page', $data);

Security Model

The policy determines which constructs templates may use. The engine uses Policy::restricted() by default. Checks run during compilation; see The Policy API for presets and grants.

Compile-Time Restrictions

Under the default policy, the following are rejected at compile time (the template won't compile):

{{ strtoupper(name) }}                 {# ERROR: unregistered function calls #}
{{ file_get_contents('/etc/passwd') }} {# ERROR #}
{{ user.getName() }}                   {# ERROR: method calls #}
{{ `ls -la` }}                         {# ERROR: backticks, heredocs, PHP tags #}
{{ new DateTime() }}                   {# ERROR: needs the 'newExpressions' rule #}
{{ Foo::create() }}                    {# ERROR: needs the 'staticCalls' rule #}
{{ Foo\Bar }}                          {# ERROR: a class name is not a value #}

Object and Value Handling

render() passes scope values to the template as-is; it does not convert objects to arrays or other template-specific values. a.b reads an object property, while a:b reads an array key. PHP visibility rules apply:

class User {
    public $name = 'John';
    private $password = 'secret';
}

$user = new User();
$engine->render('page', ['user' => $user]);
{{ user.name }}       {# 'John' — real property read #}
{{ user:name }}       {# ERROR: a key read on an object #}
{{ user.getName() }}  {# COMPILE ERROR: method calls not allowed #}
class User {
    public string $name = 'Jane';
    private string $secret = 'hidden';
}
{% for key, value in user %}
    [{{ key }}={{ value }}]
{% endfor %}
{# [name=Jane] — iteration includes public properties only #}

Traversable objects are iterated as containers. A value object with no public properties that implements Stringable retains its string form, so length of a Money object counts the characters returned by __toString(). A DateTimeInterface value remains an object for the date filter; scalars and null pass through unchanged.

Lambda Security

Lambdas in map, filter, reduce only accept:

  1. Lambda expressions (parsed at compile time)
  2. Filter references (validated at compile time)

Example:

{{ items |> map(i => i:name) }} {# Lambda: safe #}
{{ items |> map("upper") }}     {# Filter reference: safe #}

Registered Filters/Functions

Only registered filters and functions are callable under the default policy:

$engine->addFilter('customFilter', $callable);
{{ value |> customFilter }} {# Allowed: registered #}
{{ value |> notRegistered }} {# ERROR: not registered #}

A policy can also allow PHP functions to be called by their own name, without registering them. Granting a name turns the phpFunctions rule on as it grants, so one call is enough — and because the allowlist is non-empty, only the names you list resolve:

use Clarity\Engine\Policy;

$engine->setPolicy(Policy::default()->allowFunctions('strtoupper', 'count'));

Policies

A policy answers one question: what is this template allowed to reach? It is a set of rules plus two allowlists, and the default is sandboxed:

use Clarity\Engine\Policy;

$engine->setPolicy(Policy::restricted());    // the default
$engine->setPolicy(Policy::trusted());       // PHP function calls, method calls, superglobals, PHP locals
$engine->setPolicy(Policy::unrestricted());  // every rule
$engine->setPolicy(
    Policy::default()
        ->allowFunctions('strtoupper', 'count')
);

Rules expose different levels of access, and each names one construct.

PHP function calls in template expressions need the phpFunctions rule — granted on its own, or automatically by allowFunctions().

Raw {% php %} blocks need the separate rawPhp rule.

Policy::unrestricted() allows every rule, so use it only for templates written and reviewed by trusted authors.

Use denyFunctions() to reject named PHP functions in template expressions, when the policy otherwise allows them:

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

It does not inspect calls inside raw {% php %} blocks; those are emitted as PHP and are governed by rawPhp alone.

Two details apply across policies:

  • Clarity reserves __c_ names for its own bindings. Template-level variable bindings cannot shadow them; dynamic-variable reads resolve against the render scope and loop locals.
  • Superglobals require a separate grant. Without it, {{ _SERVER }} is a scope read and throws if that name is absent, even when phpVariables is enabled.

See The Policy API for the rule and allowlist reference.

Performance Optimization

Pre-Compilation

Render every template once after deployment so the first user request does not pay for it. Use data, not an empty array: under the default policy a template that reads any variable throws on its first read, and a fixture render is also what catches a typo, a missing filter, a bad {% include %} and a syntax error at deploy time:

$fixtures = [
    'layouts/main' => ['title' => 'x', 'content' => ''],
    'pages/home'   => ['title' => 'x', 'items' => [['id' => 1]]],
];
foreach ($fixtures as $template => $data) {
    $engine->render($template, $data);   // warms the template and everything it includes
}

Compilation alone cannot see a variable name, so this is the only stage that can (see Troubleshooting).

Cache in Persistent Storage

Use a persistent cache directory (not /tmp):

$engine->setCachePath('/var/cache/clarity');

Ensure it survives server restarts.

OPcache Configuration

Enable OPcache in production (php.ini):

opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2

Minimize Template Complexity

  • Keep logic simple (complex logic in PHP, not templates)
  • Avoid deeply nested loops
  • Cache computed values in PHP before passing to template

Configuration Reference

Configuration Methods

Method Description
setViewPath(string $path) Base directory for templates
setLayout(?string $layout) Default layout template
setExtension(string $ext) File extension (default: .clarity.html)
setCachePath(string $path) Cache directory
getCachePath(): string Get current cache path
setPolicy(Policy|array $policy) What templates may reach (default: sandboxed)
getPolicy(): Policy The current policy
isSandboxed(): bool Whether the policy lets templates reach PHP at all
flushCache(): void Delete all cached files
addFilter(string $name, callable $fn) Register custom filter
addFunction(string $name, callable $fn) Register custom function
setLoader(TemplateLoader $loader) Set custom template loader
render(string $view, array $vars): string Render template and return HTML

Example: Complete Setup

use Clarity\ClarityEngine;
use Clarity\Engine\Directive;

$engine = new ClarityEngine();

// Paths
$engine->setViewPath(__DIR__ . '/views');
$engine->setCachePath(__DIR__ . '/cache/clarity');

// Default layout
$engine->setLayout('layouts/main');

// Domain-based loader (admin:: and emails:: prefixes, plus fallback)
$engine->setLoader(new \Clarity\Template\DomainRouterLoader(
    [
        'admin'  => new \Clarity\Template\FileLoader(__DIR__ . '/views/admin'),
        'emails' => new \Clarity\Template\FileLoader(__DIR__ . '/views/emails'),
    ],
    fallback: new \Clarity\Template\FileLoader(__DIR__ . '/views'),
));

// Custom filters
$engine->addFilter('currency', fn($v) => '€ ' . number_format($v, 2));
$engine->addFilter('excerpt', fn($text, $len = 100) =>
    mb_strlen($text) > $len ? mb_substr($text, 0, $len) . '...' : $text
);

// Custom functions
$engine->addFunction('asset', fn($path) => '/assets/' . ltrim($path, '/'));

// Render
echo $engine->render('pages/home', [
    'title' => 'Home',
    'user' => $user,
]);

Modules

Modules are the recommended way to bundle related filters, functions, block directives, and services into a single reusable unit:

use Clarity\Localization\IntlFormatModule;
use Clarity\Localization\TranslationModule;

$engine->addModule(new IntlFormatModule(['locale' => 'de_DE', 'timezone' => 'Europe/Berlin']));
$engine->addModule(new TranslationModule([
    'locale'            => 'de_DE',
    'fallback_locale'   => 'en_US',
    'translations_path' => __DIR__ . '/locales',
]));

The built-in localization modules provide:

  • IntlFormatModule — locale-aware number, currency, date and text filters backed by PHP's intl extension: format_number, format_currency, percent, spellout, ordinal, format_date, format_relative, country_name, format_message, …
  • TranslationModule — a t filter for lookup in domain-separated locale files (PHP, JSON, YAML) plus the {% with_t_domain %} block for domain switching
  • LocaleService — a push/pop locale stack with the {% with_locale %} block; optional, since the other two modules bootstrap it. Register it to set an application-wide default locale for modules that configure none (a module's own locale still wins)

Custom modules implement Clarity\ModuleInterface with a single register(ClarityEngine $engine): void method.

Full module reference →

Debug Mode

Use setDebugMode() to control debug mode.

$engine->setDebugMode(true);                              // full debug, defaults
$engine->setDebugMode(new DumpOptions(maxDepth: 3));      // …with options
$engine->setDebugMode(false);                             // production

DumpOptions is set two ways that compose: named arguments in the constructor, or a fluent call of the same name. The chain mutates the instance and returns it, so options handed to the engine stay adjustable afterwards:

use Clarity\Debug\DumpOptions;

$opts = (new DumpOptions())
    ->maxDepth(4)                        // nesting depth before `…`
    ->maxItems(20)                       // items shown per level
    ->maskKeys(['password', 'token'])    // replace the mask list…
    ->maskKey('secret')                  // …or add / remove single entries
    ->unmaskKey('apikey')
    ->showPanel();                       // inject the HTML debug panel

$engine->setDebugMode($opts);

$opts->maxDepth(2);                      // still applies, next render onward
Option Method / argument Default Effect
$maxDepth maxDepth(int) 5 Nesting depth rendered before values become …
$maxItems maxItems(int) 50 Items shown at any one level (HTML and CLI)
$maskKeys maskKeys(array), maskKey(string), unmaskKey(string) password, token, secret, apikey, api_key Key substrings whose values are hidden, case-insensitively
$forceToTemplate forceToTemplate(bool) false CLI renderer returns the string instead of writing to STDERR
$showPanel showPanel(bool) false Subscribe the HTML debug panel to the event bus
$haltWithException haltWithException(bool) false dd() throws DumpHaltException instead of exiting; see dd() and halt mode

The boolean setters take no argument as shorthand for true, so ->showPanel() reads as a command; ->showPanel(false) turns it off.

When active:

  • dump() is rendered context-aware
    • an HTML tree in HTML
    • a JavaScript ;/* DEBUG_DUMP: … */ comment inside <script>
    • a CSS /* DEBUG_DUMP: … */ comment inside <style>
    • with the keys listed in DumpOptions::maskKeys() masked (password, token, secret, …).
  • {{ x |> dump }} dumps the piped value at the pipe position and still yields it, so {{ items |> dump |> length }} measures items.
  • {{ map(items, "dump") }} works as a callable reference too.
  • Range-loop safety checks run at runtime: a step of 0, or a step moving away from the end (which would loop forever), throws a RuntimeException.
  • A DebugEventBus reports template resolution, compilation, cache hits and rendering; see below for event details and subscriptions.
// Check whether debug mode is currently on
$engine->isDebugMode(); // bool

Debug events

getDebugBus() returns the active bus (or null when debug mode is off). Subscribe either a callable or a DebugListener; listeners run synchronously when an event is emitted. The bus keeps the 1000 most recent events in getEvents(); older events are dropped. A DebugEvent has a type, a metadata payload, and a Unix timestamp:

Event Payload
template.resolve template, loader class
template.compile template, duration_ms
template.cached template (compiled template served from cache)
template.render template, duration_ms

The bus reports template lifecycle metadata, not template variables or dump values. new DumpOptions(showPanel: true) — or ->showPanel() on an existing instance — automatically subscribes the floating HTML panel to the same events and appends it to the rendered output.

Dump renderers

For ordinary dump() calls, the template's output context selects the renderer; running PHP from the CLI does not by itself switch a template dump to the CLI format.

Renderer Output
HTML A collapsible <details> tree, with escaped scalar text. Each render includes the inline CSS.
JavaScript JSON inside a ;/* DEBUG_DUMP: … */ comment, safe to place between script statements; closing */ sequences in values are escaped, and < and > are written as \u003C and \u003E.
CSS JSON inside a /* DEBUG_DUMP: … */ comment; closing */ is escaped and tag delimiters are JSON-hex-encoded to protect the surrounding <style> element.
CLI A nested text tree, ANSI-colored when the output stream supports it (VT100 on Windows, a TTY elsewhere) and plain otherwise. dd() uses this renderer under CLI/phpdbg, writes to standard error, and exits (or throws in halt mode); CliDumpRenderer::render() writes to standard error by default, or returns the string when forceToTemplate(true) is set.

HTML and CLI output truncate nested values at maxDepth and limit each array to maxItems. JavaScript output also truncates at maxDepth, but serializes all array items. CSS comments also truncate at maxDepth and serialize all array items. Matching mask keys are case-insensitive substrings of array keys and object property names. Objects are shown by their properties, and JsonSerializable values in JavaScript and CSS output are masked on their serialized data. Closures and enums are not expanded. The list itself is replaced by maskKeys([…]) and adjusted one entry at a time by maskKey() and unmaskKey().

dd() and halt mode

By default dd() writes the dump and calls exit(1). That suits a one-shot request, but it also ends a long-running worker process (RoadRunner, Swoole, Octane-style hosts).

With haltWithException(true), dd() throws Clarity\Debug\DumpHaltException instead. The exception carries the rendered dump:

  • $e->output: the rendered dump string
  • $e->context: html, js or css

Halt mode applies on every SAPI, including CLI. Enable it only in hosts that catch the exception:

$engine->setDebugMode((new DumpOptions())->haltWithException(true));

The RoadRunner adapter (RoadRunnerHttpWorker in azera-roadrunner) catches the exception and returns the dump as a 500 response, with a Content-Type that matches the context. Its bootstrap enables halt mode for the HTTP worker automatically (WorkerBootstrap::enableDumpHalt()). The gRPC worker does not enable it, because it does not catch the exception. Other hosts should do the same.

Warning: code that catches Throwable will also catch DumpHaltException and continue running. Rethrow it there.

Everything debug is compile-time or zero-cost in production: dump() is pruned to '' — including the filter and reference forms, which collapse to the identity — so a debug chain left in a template costs nothing and prints nothing.

Tip: Enable debug mode in development and disable it in production to keep generated code lean. dd() is an exception: it is never pruned, so with debug off it throws rather than dumping raw, unmasked values.

Debug dump example:

Debug panel example:

Inline Filters

Inline filters are compiled directly into the generated PHP expression — no callable is invoked at runtime, making them zero-overhead alternatives to regular filters.

Registering an Inline Filter

$engine->addInlineFilter('dollars', [
    'php'     => '\number_format({1}, 2, ".", ",") . " USD"',
]);

With Parameters

$engine->addInlineFilter('pad', [
    'php'      => '\str_pad({1}, {2}, {3}, \STR_PAD_LEFT)',
    'params'   => ['length', 'char'],
    'defaults' => ['char' => "' '"],
]);

The template:

{{ invoiceNumber |> pad(8, '0') }}

Compiles to: \str_pad($vars['invoiceNumber'], 8, '0', \STR_PAD_LEFT) — no function lookup at runtime.

Template Syntax

Placeholder Meaning
{1} The piped value
{2} First additional parameter
{3} Second additional parameter, etc.

Registering an Inline Function

addInlineFunction() uses the same record format to register a call-only name; pipe syntax is rejected at compile time. Use it when the compiler must inspect an argument as source code rather than transform its value:

$engine->addInlineFunction('isset', [
    'php'       => 'isset({1})',
    'callGuard' => 'presence',
]);
{{ isset(user:email) }}    {# compiles to isset($__c_va['user']['email']) #}
{{ user:email |> isset }}  {# compile error: 'isset' is a function, not a filter #}

The callGuard validates that the first argument is a name or a chain, as required by PHP's isset(). This prevents invalid generated PHP: without the guard, isset(1 + 1) would fail to parse on first render instead of being rejected at compile time.

Custom Directives

Directives extend the template compiler with custom {% keyword %} tags. They are compiled at build time and emit raw PHP code.

Registering Directives

$cache = new class {
    private array $keyStack = [];
    private array $items = [];

    public function pushKey(string $key): void
    {
        $this->keyStack[] = $key;
    }

    public function currentKey(): string
    {
        if ($this->keyStack === []) {
            throw new \LogicException('No active cache key.');
        }

        return $this->keyStack[array_key_last($this->keyStack)];
    }

    public function popKey(): void
    {
        if ($this->keyStack === []) {
            throw new \LogicException('No active cache key to pop.');
        }

        array_pop($this->keyStack);
    }

    public function has(): bool
    {
        return array_key_exists($this->currentKey(), $this->items);
    }

    public function get(): string
    {
        return $this->items[$this->currentKey()];
    }

    public function set(string $value): void
    {
        $this->items[$this->currentKey()] = $value;
    }

};

// Register the cache service with the engine.
// Directives can access the cache service via $this->services['cache'].
$engine->addService('cache', $cache);

$engine->addDirective('cache', function(string $rest, TemplateLocation $at, callable $processExpr): string {
    $param = $processExpr(trim($rest));
    return <<<PHP
        \$this->services['cache']->pushKey({$param});
        try {
            if (\$this->services['cache']->has()) {
                echo \$this->services['cache']->get();
            } else {
                ob_start();
    PHP;
}, Directive::opens('endcache'));

$engine->addDirective('endcache', function(string $rest, TemplateLocation $at, callable $expr): string {
    return <<<PHP
                \$__cached = ob_get_clean();
                \$this->services['cache']->set(\$__cached);
                echo \$__cached;
            }
        } finally {
            \$this->services['cache']->popKey();
        }
    PHP;
}, Directive::closes('cache'));

The service is registered under cache, matching the $this->services['cache'] lookups emitted by the directives. The cache hit check happens before the template block, so the block is skipped entirely on a hit. The try/finally always pops the active key, including when rendering the block throws, and the service-owned stack supports nested cache blocks. The in-memory example keeps values only while this service instance lives; use a persistent cache implementation with the same has(), get(), set(), pushKey(), currentKey(), and popKey() methods to share cached values across requests.

Example usage:

{% cache 'homepage:featured' %}
    <h2>{{ featuredTitle }}</h2>
    <h3>{{ "now" |> date("Y-m-d H:i:s") }}</h3>
{% endcache %}

The $processExpr callable converts the cache-key expression (a variable or literal) to a PHP expression string.

Paired Directives

A directive that wraps a body declares its role with a Clarity\Engine\Directive value. The factory name states the role:

Factory The tag … Effect
Directive::opens('endcache', 'elsecache') opens the construct and names its parts one closer (a single named argument) plus any optional branch tags
Directive::branches('cache') is a branch segment of cache like cacheelse ends the current body, starts the next; the construct stays open
Directive::closes('cache') ends cache like endcache the construct is popped
Directive::inside('cache') may appear only inside cache an ordinary leaf, restricted in place
$engine->addDirective('cache',     $openHandler,   Directive::opens('endcache', 'elsecache'));
$engine->addDirective('elsecache', $branchHandler, Directive::branches('cache'));
$engine->addDirective('endcache',  $closeHandler,  Directive::closes('cache'));
$engine->addDirective('cacheopt',  $leafHandler,   Directive::inside('cache'));

The factories describe two concepts. opens(), branches(), and closes() define structure: they change which construct the compiler considers open. inside() defines containment: the tag does not open or close a body and is valid only within its owner. Containment is checked against the innermost open construct and is allowed across an {% include %} boundary because included templates are inlined into the same render body.

The opener defines the construct's structure. branches() and closes() validate that definition without changing it. For example, registering endcache as a branch when cache declares it as a closer causes a registration error. This validation also detects a closer registered without a corresponding opener at compile time.

Handler Signature

function (
    string           $rest,        // text after the keyword inside {% … %}
    TemplateLocation $at,          // where the tag sits: name, line and file
    callable         $processExpr  // Clarity expression(s) → PHP expression(s)
): string                          // must return PHP statement(s) to emit

$at is a Clarity\Template\TemplateLocation carrying the logical template name, the line, and the template path if available. It can be used to raise a ClarityException:

$engine->addDirective('cache', function (string $rest, TemplateLocation $at, callable $processExpr): string {
    if (trim($rest) === '') {
        throw new ClarityException('cache needs a key', $at);
    }
    return "\$this->services['cache']->begin({$processExpr(trim($rest))});";
}, Directive::opens('endcache'));

Directive Arguments

$processExpr($rest) compiles one Clarity expression to PHP by default. When a tag takes a list of arguments, for example: {% cache "user_" ~ id, ttl: 300, tags: ["user"] %} call $processExpr($rest, true) to obtain a list instead, sharing the same grammar and rules with the filter syntax:

[name: ] expr [, [name: ] expr ...]

It returns two arrays: [positional, named]. Both are lists of compiled PHP expressions, keyed by numeric index and by name:

$engine->addDirective('cache', function (string $rest, TemplateLocation $at, callable $processExpr): string {
    [$positional, $named] = $processExpr($rest, true);

    $key  = $positional[0] ?? null;   // "user_" ~ id  → the first unnamed argument
    $ttl  = $named['ttl']  ?? '300';  // ttl: 300
    $tags = $named['tags'] ?? '[]';   // tags: ["user"]

    return "\$this->services['cache']->begin({$key}, {$ttl}, {$tags});";
}, Directive::opens('endcache'));

Arguments beginning with name: are named; other arguments are positional and receive the next numeric index. Positional arguments cannot follow named arguments. Named arguments must be unique, and empty arguments (a,,b) are rejected. Commas inside quoted strings ("a,b"), literals such as {a: 1, b: 2}, and nested calls such as fn(x, y) do not split arguments.

The __c_ prefix

The engine reserves the __c_ prefix for its own internal variables. Therefore, template authors should not bind a __c_-prefixed name.

Services

Services are arbitrary objects registered into the engine and made available inside compiled templates via $this->services['key']. They're primarily used by modules to share mutable state (e.g. a locale stack or cache object) between registered filters/directives and inline filter PHP templates.

Note: Services are an infrastructure for module authors: An application that simply registers filters and functions may not need to use any services at all.

Registering a Service

$myService = new MyStatefulService();

$engine->addService('my_service', $myService);

Checking and Retrieving Services

if ($engine->hasService('my_service')) {
    $svc = $engine->getService('my_service');
}

Accessing Services in Inline Filters

Inline filter PHP templates can reference services via $this->services['key']:

$engine->addInlineFilter('t', [
    'php'     => "\$this->services['translator']->get(\$this->services['locale']->current(), {1})",
    'params'  => ['vars'],
    'defaults'=> ['vars' => 'null'],
]);

Next Steps