Best Practices
This guide provides recommendations for organizing templates, naming conventions, security, testing, and debugging Clarity templates.
Template Organization
Directory Structure
Organize templates by purpose and hierarchy:
views/
├── layouts/ # Reusable page layouts
│ ├── base.clarity.html
│ ├── main.clarity.html
│ └── admin.clarity.html
├── pages/ # Full page templates
│ ├── home.clarity.html
│ ├── about.clarity.html
│ └── contact.clarity.html
├── partials/ # Reusable components
│ ├── header.clarity.html
│ ├── footer.clarity.html
│ ├── nav.clarity.html
│ └── user-card.clarity.html
├── components/ # UI components
│ ├── buttons/
│ │ ├── primary.clarity.html
│ │ └── secondary.clarity.html
│ └── forms/
│ ├── input.clarity.html
│ └── select.clarity.html
└── emails/ # Email templates
├── layouts/
│ └── email-base.clarity.html
├── welcome.clarity.html
└── reset-password.clarity.html
Feature-Based Organization
For larger applications, organize by feature:
views/
├── layouts/
│ └── main.clarity.html
├── products/
│ ├── index.clarity.html
│ ├── show.clarity.html
│ └── partials/
│ └── product-card.clarity.html
├── users/
│ ├── profile.clarity.html
│ ├── settings.clarity.html
│ └── partials/
│ └── avatar.clarity.html
└── admin/
├── layouts/
│ └── admin.clarity.html
└── users/
├── index.clarity.html
└── show.clarity.html
Use DomainRouterLoader for separation:
use Clarity\Template\DomainRouterLoader;
use Clarity\Template\FileLoader;
$engine->setLoader(new DomainRouterLoader(
[
'products' => new FileLoader(__DIR__ . '/views/products'),
'admin' => new FileLoader(__DIR__ . '/views/admin'),
],
fallback: new FileLoader(__DIR__ . '/views'),
));
Layouts vs. Partials
Layouts (use {% extends %}):
- Define page structure (header, footer, sidebar)
- Establish visual hierarchy
- One layout per page
Partials (use {% include %}):
- Reusable components (navigation, cards, forms)
- Can be used multiple times on a page
- No page structure, just fragments
Security Best Practices
Always Rely on Auto-Escaping
Correct:
<p>{{ user:bio }}</p>
<h1>{{ pageTitle }}</h1>
Auto-escaping protects against XSS by default.
Use raw Sparingly
Dangerous:
{{ userInput |> raw }}
Safe:
{# Only with trusted, sanitized content #}
{{ sanitizedArticleBody |> raw }}
{# Or content you control #}
{{ renderedWidget |> raw }}
{{ data |> json |> raw }}
Sanitize in PHP, Not Templates
Bad:
{# Don't sanitize in templates #}
{{ userBio |> strip_tags |> raw }}
Good:
// Sanitize in PHP
$sanitized = strip_tags($user->bio, '<p><br><strong><em>');
$engine->render('profile', ['userBio' => $sanitized]);
{# Template assumes clean data #}
{{ userBio |> raw }}
Validate File Paths
The engine resolves every template name inside the view path and refuses one that would leave it, so a name cannot read an arbitrary file:
$template = $engine->render($_GET['template'] ?? 'home', $data);
// '../app/config' and '/etc/passwd.clarity.html' are both refused
Path containment prevents traversal, but an in-root template may still be one a visitor should not access. Validate the name against an application allowlist to avoid unintended templates and failed requests:
Recommended:
$allowedTemplates = ['home', 'about', 'contact'];
$template = $_GET['template'] ?? 'home';
if (!in_array($template, $allowedTemplates, true)) {
$template = 'home';
}
$engine->render($template, $data);
Custom loaders must enforce path containment. Compiler checks are only a second layer; see
FileLoader.
Never Trust User Data
Clarity auto-escapes by default, so even unsanitized input is safe in most cases
— be cautious only with |> raw. Validate at the boundary anyway so the
template receives data in the shape it expects:
// Good: validate and give the template a defined value
$engine->render('search', [
'query' => trim((string) ($_GET['q'] ?? '')),
]);
Performance Best Practices
Keep Templates Simple
Bad: Complex logic in templates
{% set filteredUsers = users
|> filter(u => u:age >= 18 and u:active and u:role == 'member')
|> map(u => { name: u:firstName ~ ' ' ~ u:lastName, email: u:email
|> lower, joined: u:createdAt
|> date('Y-m-d') }) %}
Good: Logic in PHP
$filteredUsers = array_map(function($u) {
return [
'name' => $u->firstName . ' ' . $u->lastName,
'email' => strtolower($u->email),
'joined' => date('Y-m-d', $u->createdAt),
];
}, array_filter($users, fn($u) =>
$u->age >= 18 && $u->active && $u->role === 'member'));
$engine->render('users', ['users' => $filteredUsers]);
{% for user in users %}
<li>{{ user:name }} ({{ user:email }})</li>
{% endfor %}
Avoid Deep Nesting
Bad:
{% if user %}
{% if user:isActive %}
{% if user:hasPermission %}
{% for item in user:items %}
{% if item:isPublished %} {# Deeply nested #} {% endif %}
{% endfor %}
{% endif %}
{% endif %}
{% endif %}
Good: Flatten in PHP
$publishedItems = $user && $user->isActive && $user->hasPermission
? array_filter($user->items, fn($i) => $i->isPublished)
: [];
$engine->render('items', ['items' => $publishedItems]);
{% for item in items %}
{# Simple, flat loop #}
{% endfor %}
Persistent Cache Directory
Development:
$engine->setCachePath(__DIR__ . '/cache/clarity');
Production:
$engine->setCachePath('/var/cache/clarity'); // Survives restarts
Code Style
Indentation
Use consistent indentation (2 or 4 spaces):
{% if condition %}
<div>
{% for item in items %}
<p>{{ item:name }}</p>
{% endfor %}
</div>
{% endif %}
Whitespace Around Delimiters
Preferred:
{{ variable }}
{% for item in items %}
Avoid:
{{variable}}
{%for item in items%}
Testing Templates
Unit Testing (PHP)
Test rendering with various data:
use PHPUnit\Framework\TestCase;
use Clarity\ClarityEngine;
class TemplateTest extends TestCase
{
private ClarityEngine $engine;
protected function setUp(): void
{
$this->engine = new ClarityEngine();
$this->engine->setViewPath(__DIR__ . '/views');
$this->engine->setCachePath(__DIR__ . '/cache');
}
public function testUserProfile(): void
{
$output = $this->engine->render('user-profile', [
'userName' => 'John Doe',
'userEmail' => 'john@example.com',
]);
$this->assertStringContainsString('John Doe', $output);
$this->assertStringContainsString('john@example.com', $output);
}
public function testAutoEscaping(): void
{
$output = $this->engine->render('test', [
'html' => '<script>alert("xss")</script>',
]);
$this->assertStringContainsString('<script>', $output);
$this->assertStringNotContainsString('<script>', $output);
}
}
Integration Testing
Test with real data:
public function testProductListing(): void
{
$products = Product::all()->toArray();
$output = $this->engine->render('products/index', [
'products' => $products,
]);
foreach ($products as $product) {
$this->assertStringContainsString($product['name'], $output);
}
}
Visual Regression Testing
For complex UIs, consider snapshot testing:
public function testProductCard(): void
{
$output = $this->engine->render('components/product-card', [
'product' => ['name' => 'Widget', 'price' => 19.99],
]);
$this->assertMatchesSnapshot($output);
}
Debugging
Dump Variables
Use the dump() function for debugging (renders a masked, context-aware tree
while debug mode is on; outputs nothing in production):
<pre>{{ dump(user) }}</pre>
<pre>{{ dump(products, settings) }}</pre>
Display All Variables
<pre>{{ vars() |> json |> raw }}</pre>
Check Variable Existence
{% if user is defined %}
<p>User exists: {{ user.name }}</p>
{% else %}
<p>No user provided</p>
{% endif %}
Inspect Filter Output
Chain dump in a filter pipeline — it dumps the value and passes it through
unchanged, so the following steps still see it (and the whole step disappears in
production):
{# See the intermediate result without changing it #}
{{ items |> filter(i => i:active) |> dump |> slice(0, 5) }}
map(items, "dump") works too, when you want a dump per element.
Enable Error Display (Development)
if ($_ENV['APP_ENV'] === 'development') {
ini_set('display_errors', '1');
error_reporting(E_ALL);
}
Clear Cache When Stuck
$engine->flushCache();
Reusability Patterns
Partial Templates
Extract reusable components:
File: partials/user-avatar.clarity.html
<div class="avatar">
<img
src="{{ user:avatar |> default('/images/default-avatar.png') }}"
alt="{{ user:name }}"
/>
</div>
Usage:
{% include "partials/user-avatar" %}
Parameterized Partials
Pass variables to includes using include() function:
File: components/button.clarity.html
<button
class="btn btn-{{ type |> default('primary') }}"
type="{{ buttonType |> default('button') }}"
>
{{ label }}
</button>
Usage:
{{ include("components/button", {
label: "Submit", type: "success",
buttonType: "submit"
}) }}
{{ include("components/button", { label: "Cancel", type: "secondary" }) }}
Layout Slots
Create flexible layouts with multiple slots:
File: layouts/two-column.clarity.html
<div class="two-column-layout">
<aside class="sidebar">{% block sidebar %}{% endblock %}</aside>
<main class="content">{% block content %}{% endblock %}</main>
</div>
Usage:
{% extends "layouts/two-column" %}
{% block sidebar %}
<h3>Categories</h3>
<ul>
...
</ul>
{% endblock %}
{% block content %}
<h1>Article Title</h1>
<p>Article content...</p>
{% endblock %}
Version Control
Git Ignore
Ignore cache files:
# .gitignore
cache/clarity/
*.php.cache
Template Versioning
Include version/timestamp in asset URLs:
$engine->addFunction('asset', function($path) {
static $version = null;
$version ??= filemtime(__DIR__ . '/public/assets');
return "/assets/$path?v=$version";
});
<link rel="stylesheet" href="{{ asset('css/main.css') }}" />
{# Outputs: /assets/css/main.css?v=1234567890 #}
Next Steps
- Troubleshooting — Common errors and solutions
- Examples — See best practices in action
- Advanced Topics — Deep dives into features