Documentation

Troubleshooting Guide

This guide helps you diagnose and fix common issues when working with Clarity templates.

Common Errors

TypeError: Argument must be of type string

Error:

Clarity\ClarityException: mb_strtoupper(): Argument #1 ($string) must be of type
string, null given

Cause: A template passed a value of the wrong type into a filter or function. strictTypes is on by default, so a compiled template declares declare(strict_types=1) and a mismatched argument throws instead of being coerced. The most common form is a value that may be null reaching a string filter: {{ maybeMissing |> upper }} renders '' in weak mode and throws here. The exception names the template line.

Fix: Give the value a real type at the boundary:

{{ maybeMissing |> default('') |> upper }}

default('') handles both a null from the scope and a name the scope does not contain (a name absent from both the scope and the loop locals is a compile-time error on its own, which the filter chain suppresses).

To restore PHP's old coercing behaviour instead, deny the rule — it is one rule, so nothing else opens up:

$engine->setPolicy(Policy::default()->denyRule('strictTypes'));

See strictTypes and Why strict by default.


Undefined Variable

Error:

Clarity\ClarityException: Variable "variableName" is not defined in this context

Cause: Variable not passed to template or typo in variable name. strictVariables is on by default, so a read of an absent name aborts the render instead of yielding an empty string; the exception names the template and line.

Solutions:

  1. Pass the variable to render():
$engine->render('page', [
    'variableName' => $value,  // Make sure it's included
]);
  1. Use default filter:
{{ variableName |> default('Default Value') }}
  1. Check with conditional:
{% if isset(variableName) %}
    {{ variableName }}
{% else %}
    No value provided
{% endif %}
  1. Use null coalescing operator:
{{ variableName ?? 'Default' }}
  1. Relax the rule for the whole policy — then an absent name reads as null, and {% if variableName %} needs neither ?? nor isset():
$engine->setPolicy(Policy::default()->denyRule('strictVariables'));

Only the chain root becomes tolerant: {{ variableName }} and {% if variableName %} read null, while a mistyped member (user.nope) or a wrong operator (user.name on an array) still throws. See strictVariables.


Undefined Filter

Error:

Filter 'filterName' is not registered, and this policy does not allow PHP 
function calls, so there is nothing for it to resolve to. Register it with 
addFilter(), or grant the 'phpFunctions' rule and add the name with 
allowFunctions().

Cause: Typo in filter name, or the filter was never registered.

The error occurs during compilation, not rendering.

Fix: Register a custom filter with addFilter(). To use a PHP function by name, grant the phpFunctions rule and allowlist the function (which allowFunctions() does in one step):

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

See the policy reference for details.

Also check the filter name and available built-ins:

{{ value |> upper }}

See Built-in Filters.


Template Not Found

Error:

Template 'templateName' not found

Cause: Incorrect template path or file doesn't exist.

Solutions:

  1. Check file exists:
ls views/templateName.clarity.html
  1. Verify view path:
$engine->setViewPath(__DIR__ . '/views');
echo $engine->getViewPath();  // Check the actual path
  1. Check file extension:
// Default extension is .clarity.html
$engine->render('home', []);  // Looks for home.clarity.html

// If using custom extension:
$engine->setExtension('.tpl.html');
  1. Use correct namespace:
{# Wrong #}
{% include "admin/sidebar" %}
{# Correct with namespace #}
{% include "admin::sidebar" %}

Circular Include Detected

Error:

Circular include detected: template1 → template2 → template1

Cause: Template includes itself directly or indirectly.

Example:

{# templates/a.clarity.html #}
{% include "b" %}
{# templates/b.clarity.html #}
{% include "a" %} {# Circular! #}

Solution: Refactor to break the circular dependency:

{# templates/a.clarity.html #}
{% include "c" %}
{# templates/b.clarity.html #}
{% include "c" %}
{# templates/c.clarity.html #}
<div>Shared content</div>

Class Not Found / Autoload Error

Error:

Fatal error: Class 'Clarity\ClarityEngine' not found

Cause: Composer autoload not included or dependencies not installed.

Solutions:

  1. Include autoloader:
require_once __DIR__ . '/vendor/autoload.php';

use Clarity\ClarityEngine;
  1. Install dependencies:
composer install
  1. Regenerate autoloader:
composer dump-autoload

Permission Denied (Cache Directory)

Error:

Warning: file_put_contents(...): Permission denied

Cause: Cache directory not writable by web server.

Solutions:

  1. Create directory:
mkdir -p cache/clarity
  1. Set permissions:
chmod -R 755 cache/clarity
chown -R www-data:www-data cache/clarity  # Linux/Apache
  1. Verify path:
$cachePath = $engine->getCachePath();
echo "Cache path: $cachePath\n";
echo "Writable: " . (is_writable($cachePath) ? 'Yes' : 'No') . "\n";

Template Not Updating

Problem: Changes to template file don't appear in output.

Causes & Solutions:

  1. OPcache serving stale files:
// Clear OPcache
if (function_exists('opcache_reset')) {
    opcache_reset();
}

// Or flush Clarity cache
$engine->flushCache();

Restart PHP-FPM gracefully:

sudo systemctl reload php8.3-fpm
  1. Browser caching HTML:

Hard refresh: Ctrl+Shift+R (Windows/Linux) or Cmd+Shift+R (Mac)

  1. Wrong template file edited:
// Check which template is being rendered
echo $engine->getCachePath();
// Verify the template path is correct
  1. Manual cache flush:
rm -rf cache/clarity/*

Output Escaped

Problem: HTML tags appearing in output when they should not be escaped.

Solution: Add raw filter when outputting trusted HTML:

{{ sanitizedArticleBody |> raw }}

XSS Vulnerability

Problem: Script injection in output.

Example:

{# Vulnerable #}
{{ userComment |> raw }}
{# Probable output if userComment contains a script tag:
<script>
  alert("XSS");
</script>
#}
{# Safe #}
{{ userComment }}
{# Output: &lt;script&gt;alert('XSS')&lt;/script&gt; #}

Solution: Never use raw with unfiltered user input. Rely on auto-escaping for untrusted data or use a proper sanitization filter before outputting.


Cache Issues

Stale Cache in Production

Problem: Old template version served after deployment.

Solution:

  1. Flush cache after deployment:
// deploy.php
$engine->flushCache();

Or via CLI:

php -r "require 'vendor/autoload.php'; (new \Clarity\ClarityEngine())->setCachePath(__DIR__ . '/cache/clarity')->flushCache();"
  1. Restart PHP-FPM gracefully:
sudo systemctl reload php8.3-fpm
  1. Clear OPcache:
opcache_reset();

Cache Growing Too Large

Problem: Cache directory consuming disk space.

Solutions:

  1. Periodic cleanup:
# Cron job to clear old cache files
find /var/cache/clarity -type f -mtime +30 -delete
  1. Flush during deployment:
$engine->flushCache();  // Removes all cached files

Multiple Environments Sharing Cache

Problem: Development and production sharing the same cache.

Solution: Use environment-specific cache paths:

$env = $_ENV['APP_ENV'] ?? 'production';
$engine->setCachePath(__DIR__ . "/cache/clarity-{$env}");

Performance Issues

Slow First Request

Cause: Template compilation on first render.

Normal behavior: Clarity compiles templates on first request, then caches them.

Solutions:

  1. Pre-warm cache after deployment — with data, not an empty array:
// Under the default policy a template that reads a variable throws when rendered
// with no data, so warm with the same fixtures a test would use.
$fixtures = [
    'home'           => ['title' => 'Home'],
    'about'          => ['title' => 'About'],
    'contact'        => ['title' => 'Contact'],
    'products/index' => ['title' => 'Products', 'items' => []],
];
foreach ($fixtures as $template => $data) {
    $engine->render($template, $data);
}

A fixture render also fails on a variable typo, a missing filter, a broken include or a syntax error — compilation alone cannot see a variable name.

  1. Accept warm-up time: Subsequent requests will be fast.

Slow Every Request

Cause: Cache disabled or not working.

Check:

echo "Cache path: " . $engine->getCachePath() . "\n";
echo "Writable: " . (is_writable($engine->getCachePath()) ? 'Yes' : 'No') . "\n";

Solutions:

  1. Verify cache directory is writable
  2. Ensure you're NOT calling flushCache() on every request
  3. Enable OPcache (php.ini):
opcache.enable=1
opcache.memory_consumption=128

Memory Issues

Error:

Fatal error: Allowed memory size exhausted

Causes:

  1. Too much data passed to template:
// Bad: Passing huge dataset
$engine->render('page', ['items' => $millionRows]);

// Good: Paginate
$engine->render('page', ['items' => array_slice($millionRows, 0, 20)]);
  1. Infinite loop in template:
{# Long running loop #}
{% for i in 1..999999999 %}
    {{ i }}
{% endfor %}

Encoding Issues

Garbled Unicode Characters

Problem: ä instead of ä, ’ instead of '

Cause: Encoding mismatch (template not UTF-8 or output not declared UTF-8).

Solutions:

  1. Save templates as UTF-8:

In your editor: File → Save with Encoding → UTF-8

  1. Declare charset in HTML:
<meta charset="UTF-8" />
  1. Set PHP output encoding:
header('Content-Type: text/html; charset=UTF-8');
  1. Check database encoding:
// MySQL: Use UTF-8
$pdo = new PDO('mysql:host=localhost;dbname=mydb;charset=utf8mb4', ...);

Emoji Not Displaying

Problem: Emoji showing as ? or boxes.

Solutions:

  1. Use UTF-8mb4 (MySQL):
ALTER TABLE posts CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
  1. Ensure UTF-8 encoding:
<meta charset="UTF-8" />
  1. Check font support: Some fonts don't include emoji glyphs.

Debugging Techniques

Enable Error Display

Development:

ini_set('display_errors', '1');
error_reporting(E_ALL);

Production:

ini_set('display_errors', '0');
ini_set('log_errors', '1');
error_log('Template error: ' . $exception->getMessage());

Turn On Debug Mode

setDebugMode(true) turns on the full debug experience — context-aware, masked dump(), the dump filter, runtime range-loop safety checks and a render event bus:

$engine->setDebugMode(true);                    // dev
$engine->isDebugMode();                         // bool

// …or with options (depth, masking, HTML panel)
use Clarity\Debug\DumpOptions;
$engine->setDebugMode(new DumpOptions(showPanel: true, maxDepth: 99));

dump() displays a masked, context-aware tree only when debug mode is enabled. Otherwise it outputs nothing and is safe to leave in templates — see Debug Mode.

Dump Template Variables

<pre>{{ vars() |> json |> raw }}</pre>

Or specific variable:

<pre>{{ dump(user) }}</pre>

Unlike {{ vars() |> json }}, dump() does not expose data in production.

Use Try-Catch

use Clarity\ClarityException;

try {
    echo $engine->render('page', $data);
} catch (ClarityException $e) {
    echo "<pre>";
    echo "Error: " . $e->getMessage() . "\n";
    echo "Template: " . $e->templateName . "\n";
    echo "Path: " . $e->templatePath . "\n";
    echo "Line: " . $e->templateLine . "\n";
    echo "\nStack Trace:\n" . $e->getTraceAsString();
    echo "</pre>";
}

Integration Issues

Framework Conflicts

Problem: Clarity conflicts with framework's view engine.

Solution: Use namespacing or conditional initialization:

// Only initialize Clarity for specific routes
if ($request->isAdminRoute()) {
    $viewEngine = new ClarityEngine();
} else {
    $viewEngine = new FrameworkViewEngine();
}

Asset Path Issues

Problem: CSS/JS paths broken when using Clarity.

Solution: Use absolute paths or custom function:

$engine->addFunction('asset', function($path) {
    return '/assets/' . ltrim($path, '/');
});
<link rel="stylesheet" href="{{ asset('css/main.css') }}" />
<script src="{{ asset('js/app.js') }}"></script>

AJAX Rendering

Problem: Need to render partial template for AJAX response.

Solution: Disable layout for AJAX requests:

if ($request->isAjax()) {
    $engine->setLayout(null);
}

echo $engine->render('partials/user-list', ['users' => $users]);

Error Reference

Common Clarity Errors

Error Message Likely Cause Solution
Template 'X' not found Wrong path or file doesn't exist Check view path and file name
Filter 'X' not registered Typo or filter not added Register filter or check spelling
Undefined array key "X" Variable not passed to template Pass variable or use |> default
Circular include detected Template includes itself Refactor to break circular dependency
Permission denied Cache directory not writable Set correct permissions
Syntax error: unexpected token Missing delimiter or typo Check template syntax
Class 'ClarityEngine' not found Autoloader not included Include vendor/autoload.php
Memory exhausted Too much data or infinite loop Reduce data size or fix loop

Next Steps