Twig, Blade and compiled template engines share the same Achilles' heel: static analysis and code completion in views.
TwigStan is a great initiative and an ambitious project, but it faces significant technical challenges: stuck on Symfony 7.1 components, Symfony 8 migration proving very difficult (cf. issue #277). This illustrates the inherent complexity of adding static analysis on top of a compiled template language.
The Splates approach is simpler, if you accept mixing HTML and PHP: by relying directly on the native PHP ecosystem (PHPStan, IDE), you avoid this extra layer of complexity.
Splates is a modern PHP 8.4+ template engine, a fork of league/plates, redesigned around typed PHP classes. The result: PHPStan max level on templates, full IDE autocompletion, and zero magic.
Why Splates?
- Less magic: no compiled template language, no string-based template names, no magic sections. Just PHP classes.
- PHPStan max level: every template is statically analyzable. Typos are caught at analysis time, not runtime.
- IDE autocompletion: constructor parameters with
#[TemplateData]provide autocompletion everywhere. - Contextual escaping: the
Text,Html,Attr,Jsvalue objects handle escaping according to context. - Typed Slots pattern: layouts are components with
Closureproperties (replaces magicblock/section). - Service injection:
#[Inject]+Engine::addGlobal()for global services.
Quick Start
composer require piedweb/splates
Create a template:
{{ "
e($this->name) ?>
Email: e($this->email) ?>
Render it:
{{ "render(new ProfileTpl(
name: 'John Doe',
email: 'john@example.com',
));"|escape }}
The IDE autocompletes the name and email parameters. PHPStan checks the types. No surprises at runtime.
File-based templates (no class)
Splates also supports classic .php templates (like league/plates), no class needed:
{{ "render('templates/hello.php', ['name' => 'John']);"|escape }}
{{ "
Hello,
"|escape }}
Variables are automatically extracted, and $e is available as an escaping function.
This is ideal for simple templates or a progressive migration. For complex templates, classes offer type safety and autocompletion.
Class-based templates
The real strength of Splates. A template is a PHP class with:
- A constructor with
#[TemplateData] parameters: the template data - An
__invoke() method: the HTML rendering - Helper methods via
TemplateAbstract: $this->e(), $this->render(), $this->capture(), $this->slot()
{{ "
e($this->user->name) ?>
showEmail): ?>
e($this->user->email) ?>
Value objects for safe escaping
Splates provides value objects with contextual escaping:
Class Context Example TextHTML content <p><?= $text ?></p>HtmlPre-escaped HTML <?= $html ?>AttrHTML attributes <div class="<?= $attr ?>">JsJavaScript values <script>var x = <?= $js ?>;</script>
{{ "bad');
echo \"$name
\";
// <script>bad</script>
// Attr — escape for HTML attributes
$class = new Attr('my-class\" onclick=\"bad');
echo \"\";
//
// Js — JSON-encode for JavaScript
$data = new Js(['user' => 'John', 'count' => 42]);
echo \"\";
// "|escape }}
Layouts with the Slots pattern
No more magic {% extends %} and {% block %}. With Splates, a layout is a component that receives Closure properties:
The layout
{{ "
<?= $this->e($this->title) ?>
content)() ?>
scripts): ?>
scripts)() ?>
The page
{{ "render(new LayoutTpl(
title: $this->title,
content: $this->slot(function () { ?>
e($this->body) ?>
Comparison with Twig
{{ "{# Twig #}
{% extends 'layout.html.twig' %}
{% block content %}
{{ title }}
{% endblock %}" }}
With Splates, the layout is explicit: you can see exactly which slots are passed, with their types. The IDE can navigate from component to layout in one click.
Service injection
For global services (router, config, etc.), Splates uses #[Inject] and Engine::addGlobal():
{{ "addGlobal('ext', $templateExtension);
$engine->addGlobal('router', $router);"|escape }}
{{ "
e($this->ext->url('user_profile', ['id' => $this->user->getId()])) ?>\">
e($this->user->getName()) ?>
Creating a base class for the application
{{ "ext->url($route, $params);
}
protected function user(): ?User
{
return $this->ext->getUser();
}
}
// All app templates extend AppTemplate
class DashboardTpl extends AppTemplate
{
public function __invoke(): void
{ ?>
Welcome, e($this->user()?->getName() ?? 'Guest') ?>
Symfony integration
Service configuration
{{ "# config/services.yaml
services:
PiedWeb\\Splates\\Engine:
arguments:
$templateDir: '%kernel.project_dir%'
$cacheDir: '%kernel.cache_dir%/splates'
calls:
- addGlobal: ['ext', '@App\\Service\\TemplateExtension']" }}
AbstractController override
{{ "splates->render($template),
$status,
);
}
}"|escape }}
Usage in a controller
{{ "renderSplates(new ProfileTpl(user: $user));
}
}"|escape }}
Symfony forms
For forms, the most pragmatic approach is to delegate rendering to Twig via the existing bridge:
{{ "twig->render('form.html.twig', [
'form' => $form->createView(),
]);
}
}"|escape }}
Migrating from Twig to Splates
Twig Splates {% extends 'layout.html.twig' %}echo $this->render(new LayoutTpl(content: ...)){% block content %}...{% endblock %}content: $this->slot(function () { ... }){% include 'partial.html.twig' %}echo $this->render(new PartialTpl()){% macro tooltip(text) %}Private PHP method or injected service {{ var|default('fallback') }}$var ?? 'fallback'{{ var|u.truncate(50, '…') }}(new UnicodeString($var))->truncate(50, '…'){{ var|escape }} / {{ var }}$this->e($var){% for item in items %}foreach ($this->items as $item):{% if condition %}if ($condition):
Migration steps
- Create template classes: one
.twig file = one PHP class. Template variables become #[TemplateData] constructor parameters.
- Convert layouts:
{% extends %} + {% block %} become the slots pattern. The layout receives Closure properties, the page passes them via $this->slot().
- Replace includes:
{% include 'partial.html.twig' %} becomes $this->render(new PartialTpl(...)).
- Replace macros: they become
private methods on the class or services injected via #[Inject].
- Adapt filters: Twig filters become native PHP (
?? for default, UnicodeString for text manipulation, etc.).
Migrating from League/Plates to Splates
league/plates Splates new Engine('/templates', 'php')new Engine(templateDir: '/templates')$engine->render('profile', ['name' => 'John'])$engine->render(new ProfileTpl(name: 'John'))$engine->addData(['key' => 'val'])$engine->addGlobal('key', $val)$engine->registerFunction('upper', ...)Removed, use native PHP $engine->loadExtension(new Asset(...))Removed, use #[Inject] $engine->addFolder('emails', '/path')Removed, use PSR-4 namespaces $this->e($value)$this->e($value) (identical)$this->fetch('partial')$this->render(new PartialTpl())$this->layout('layout')echo $this->render(new LayoutTpl(content: ...))$this->section('content')($this->content)() in the layout$this->start('content') … $this->stop()content: $this->slot(function () { ... })
Migration steps
- Convert file templates to classes: each
.php template becomes a class extending TemplateAbstract. Variables become #[TemplateData] parameters.
- Replace layouts:
$this->layout('layout') + $this->start()/$this->stop() become echo $this->render(new LayoutTpl(content: $this->slot(...))).
- Replace includes:
$this->fetch('partial') and $this->insert('partial') become $this->render(new PartialTpl()).
- Replace extensions:
registerFunction() and loadExtension() become #[Inject] properties fed by addGlobal().
- Progressive migration: Splates still supports file templates via
$engine->render('template.php', [...]), so migration can be done file by file.
Cache and Performance
In production, enable the reflection cache to avoid introspection on every request:
{{ "getInjectResolver()->warmCache([
ProfileTpl::class,
LayoutTpl::class,
ArticleTpl::class,
]);"|escape }}
The trade-off is accepting PHP in templates, but with typed classes, value objects and the slots pattern, the result is more structured and safer than Twig without static analysis.
Continue reading
WPML, Polylang, TranslatePress, PiedWeb AI Polyglot:
which WordPress translation plugin should you choose? #WebDev Tailwind Color Matrix Visualize, test and share your Tailwind palettes #WebDev Iframe and performance #WebDev Digital Analogy Web concepts explained through everyday images #WebDev How to view the mobile version of a website on Chrome or Firefox