bugo / antlers-php
Standalone Antlers template engine — use outside Statamic/Laravel
Requires
- php: ^8.2
- symfony/string: ^7.4|^8.0
- symfony/translation-contracts: ^3.6
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.94
- pestphp/pest: ^3.8|^4.4
- phpstan/phpstan: ^2.1
- rector/rector: ^2.4
- vimeo/psalm: ^6.15
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A standalone implementation of the Antlers templating engine, designed for use outside the Statamic/Laravel ecosystem in any PHP 8.2+ project.
Positioning
antlers-php targets a standalone Antlers subset for regular PHP projects.
This means the project aims to support the core Antlers language that works predictably without Statamic or Laravel, such as variables, expressions, conditions, loops, modifiers, partials, and custom tags/modifiers.
It does not promise full compatibility with every Statamic tag, modifier, CMS feature, or Laravel-dependent integration.
In particular, {{? ?}} and {{$ $}} PHP delimiters from Statamic Antlers are intentionally not supported in antlers-php. This project keeps PHP execution out of the standalone core instead of exposing it as a template feature.
Installation
composer require bugo/antlers-php
Quick Start
use Bugo\Antlers\Engine; $engine = new Engine(); echo $engine->render('Hello, {{ name }}!', ['name' => 'World']); // → Hello, World!
Security
antlers-php does not auto-escape {{ ... }} output by default. This is intentional for standalone Antlers compatibility.
When rendering user-provided content into HTML, explicitly escape it with sanitize or entities:
{{ comment | sanitize }}
{{ email | entities }}
Treat plain {{ ... }} output as raw template output unless you have applied the escaping yourself.
The markdown tag and modifier are the exception: they are the designated transform for
untrusted prose, so raw HTML in the source is escaped and unsafe link schemes are dropped.
See Markdown Renderer.
Syntax
Variables
{{ name }}
{{ user.profile.name }}
{{ items[0] }}
{{ items[key] }}
{{ items['name'] }}
{{ matrix[1][0] }}
items[key] uses the current scope variable key as the index, while items['name'] and
items.name both read the literal key. An index can be a path of its own (items[a.b]) and
subscripts can chain (matrix[1][0]), but an index is not a full expression: items[i + 1] is a
syntax error rather than a silent miss.
A value is printed the same way everywhere — straight to output, through a modifier or through a
tag. Booleans read as true and false, an array joins its parts, null and an object without
__toString() print nothing:
{{ flag }} {{ flag | upper }} {{# true TRUE #}}
{{ parts }} {{ parts | upper }} {{# xy XY, for ['x', 'y'] #}}
Coalescing and Ternary Operator
{{ name ?? "Guest" }}
{{ power_level ??? "It's over 9000!" }}
{{ logged_in ? "Welcome back" : "Please log in" }}
?? falls back whenever the left side is falsy, using the same truthiness rules as {{ if }}:
null, false, '', '0', 0, 0.0 and empty arrays all take the fallback. This matches
Statamic, where ?? is documented as returning the first value that passes a truthy check.
??? falls back only on null, so 0, false and '' survive:
{{ v ?? "fallback" }} {{# v = 0 → fallback #}}
{{ v ??? "fallback" }} {{# v = 0 → 0 #}}
Neither operator throws for an undefined left side, even in strict mode — both are an explicit "use it if it is there".
Arithmetic and Strings
{{ price * 1.2 }}
{{ count + 1 }}
{{ "Hello" . ", " . name . "!" }}
Conditions
{{ if score > 90 }}
Excellent!
{{ elseif score > 70 }}
Good
{{ else }}
Needs improvement
{{ /if }}
{{ unless logged_in }}
<a href="/login">Log in</a>
{{ /unless }}
Loops
{{# foreach with alias #}} {{ foreach items as item }} <li>{{ item.title }}</li> {{ /foreach }} {{# foreach with key and value #}} {{ foreach data as key => value }} {{ key }}: {{ value }} {{ /foreach }} {{# statamic-compatible foreach forms #}} {{ foreach:company_info }} {{ key }}: {{ value }} {{ /foreach:company_info }} {{ foreach:song_reviews as="song|rating" }} {{ song }}: {{ rating }} {{ /foreach:song_reviews }} {{ foreach :array="reviews:songs" as="song|rating" }} {{ song }}: {{ rating }} {{ /foreach }} {{# numeric loop #}} {{ for 1 to 5 }} {{ value }} {{ /for }} {{# paired tag that iterates over an array #}} {{ posts }} <h2>{{ title }}</h2> {{ /posts }}
A paired block decides from the value's keys: all-integer keys iterate — including gaps left by
array_filter() or unset() and 1-based data — while any string key means a single item whose
fields become variables.
Variables available inside loops include:
| Variable | Description |
|---|---|
{{ count }} |
Current iteration number (starting from 1) |
{{ index }} |
Current iteration number (starting from 0) |
{{ total }} |
Total number of items |
{{ first }} |
true on the first iteration |
{{ last }} |
true on the last iteration |
{{ odd }} |
true on odd iterations |
{{ even }} |
true on even iterations |
{{ key }} |
Key of the current item |
Paired array loops also support neighbor access via colon notation:
{{ songs }}
{{ value }} (next: {{ next:value }}, prev: {{ prev:value }})
{{ /songs }}
Modifiers
{{ title | upper }}
{{ title | lower | truncate:50 }}
{{ price | multiply:1.2 | round:2 }}
{{ items | sort | first }}
{{ date | format:"d.m.Y" }}
Setting Variables
{{ set greeting = "Hello" }}
{{ greeting }}, {{ name }}!
{{ greeting = "Hello" }} is the same assignment in expression form.
An assignment writes into the innermost scope frame. Frames are opened by the render itself, by
every loop iteration, and by every partial and section body — conditions and truthy blocks are
not frames. So a value set inside {{ if }} is still there afterwards, while one set inside a
loop body is gone once that iteration ends:
{{ if user }}{{ set label = "member" }}{{ /if }}{{ label }} {{# member #}}
{{ items }}{{ set seen = title }}{{ /items }}{{ seen }} {{# empty #}}
Comments
{{# This text will not appear in the HTML output #}}
{{? ?}} and {{$ $}} are not available in this engine. If you need PHP, keep it outside Antlers templates in your application code.
Noparse
{{ noparse }}
{{ this will not be processed by the engine }}
{{ /noparse }}
Single tag: @{{ name }}
Tags
{{# self-closing tag #}} {{ greeting name="Alice" }} {{# tag with method (namespace) #}} {{ partial:header title="Welcome" }} {{# paired tag (with content) #}} {{ markdown }} **Bold** {{ /markdown }}
A registered name is a tag call in every form it can be written — with a method, with
parameters, and as a paired block without any. Names are resolved against the tag registry, so a
tag added through addTag() behaves exactly like a built-in one. A bare word after the name is a
flag parameter and arrives as true:
{{ box }}...{{ /box }} {{# paired call, no parameters #}}
{{ box flag }} {{# parameter "flag" is true #}}
A registered tag wins over a variable of the same name. Prefix the name with $ to force the
variable, or with % to force the tag:
{{ $box }}{{ value }}{{ /$box }} {{# the variable, even though a box tag exists #}}
{{ %box }} {{# the tag, even though a box variable exists #}}
A name that is not registered but is written like a tag is still reported as one, so the message names the tag instead of complaining about its parameters:
{{ cache key="home" }} {{# Unknown tag: "cache" #}}
Whether {{ name }} is an interpolation or a paired block is decided per occurrence, by
looking for the matching {{ /name }}. So the same name can be used both ways in one
template:
Total: {{ items | length }}
{{ items }}<li>{{ value }}</li>{{ /items }}
A closing tag must close the innermost open block, and every block must be closed. Crossed,
mismatched, unclosed and stray closing tags are AntlersSyntaxExceptions reporting the source
line — they are not rendered as best-effort output:
{{ if true }}A{{ /foreach }} {{# Unexpected closing tag {{ /foreach }}, expected {{ /if }} #}}
{{ if true }}A {{# Unclosed tag {{ if }} #}}
{{ /if }} {{# Unexpected closing tag {{ /if }} #}}
Every AntlersSyntaxException carries templateLine and templateSource, and repeats both in
its message, so getMessage() alone is enough to locate the problem:
Expected ")" but found end of expression on line 5 in "( 1 + 2"
Built-in Tags
The standalone core currently registers these built-in tags:
dump, foreach, increment, layout, loop, markdown, once, partial, prepend, push, scope, section, slot, stack, svg, switch, yield
set is also supported as Antlers syntax for variable assignment, but it is language syntax rather than a registered tag from CoreTags.
Core Tag Examples
{{ partial src="partials/card.antlers.html" title="Hello" }}
{{ partial:header title="Welcome" }}
{{ partial:exists src="partials/card.antlers.html" }}
{{ partial:if_exists src="partials/maybe.antlers.html" }}
{{ section:hero }}<h1>{{ title }}</h1>{{ /section:hero }}
{{ yield:hero }}
{{ yield:sidebar }}Fallback sidebar{{ /yield:sidebar }}
{{ markdown }}**Bold**{{ /markdown }}
{{ markdown:indent }}
# Title
{{ /markdown:indent }}
{{ loop times="3" }}{{ value }}{{ /loop }}
{{ loop count="3" start="5" }}{{ value }}{{ /loop }}
{{ loop:2 }}{{ value }}{{ /loop:2 }}
{{ switch between="odd|even" }}
{{ switch name="rows" in="a|b" }}
{{ scope:page }}{{ page:title }}{{ /scope:page }}
{{ dump value=user }}
{{ svg src="icons/logo.svg" }}
{{ increment }}
{{ increment:row from="10" by="5" }}
Built-in Modifiers
This project intentionally supports an official subset of Statamic modifiers that works well in a standalone PHP engine, without Laravel/Statamic runtime dependencies.
| Status | Modifiers |
|---|---|
| Supported official subset | add, ceil, chunk, contains, count, decode, divide, ends_with, entities, explode, first, flatten, floor, format, is_array, is_empty, is_numeric, join, kebab, keys, last, lcfirst, length, limit, lower, markdown, md5, mod, multiply, nl2br, pad, pluck, regex_replace, repeat, replace, reverse, round, sanitize, slugify, snake, sort, starts_with, strip_tags, studly, subtract, surround, title, trim, truncate, ucfirst, unique, upper, values, where, word_count, wrap |
Disputed Statamic Modifiers
antlers, partial, and raw are intentionally excluded from the standalone modifier API.
partialstays a tag concern in this project: usepartial,partial:exists, andpartial:if_existsinstead of a modifier.antlersis not part of the first stable standalone core because re-rendering strings as templates needs a separate execution model and explicit recursion safeguards.rawis not included becauseantlers-phpdoes not auto-escape output by default; literal/raw behavior is already covered by normal output,@{{ ... }}, andnoparse.
String
| Modifier | Description | Example |
|---|---|---|
upper |
Uppercase | {{ name | upper }} |
lower |
Lowercase | {{ name | lower }} |
title |
Title Case | {{ title | title }} |
ucfirst |
Capitalize the first character | {{ text | ucfirst }} |
lcfirst |
Lowercase the first character | {{ text | lcfirst }} |
slugify |
URL slug | {{ title | slugify }} |
snake |
snake_case | {{ name | snake }} |
studly |
StudlyCase | {{ name | studly }} |
kebab |
kebab-case | {{ name | kebab }} |
trim |
Trim whitespace | {{ text | trim }} |
truncate |
Truncate to N characters | {{ text | truncate:100:"..." }} |
limit |
Limit length | {{ text | limit:50 }} |
word_count |
Count words | {{ text | word_count }} |
replace |
Replace substring | {{ text | replace:"old":"new" }} |
regex_replace |
Replace using a regex pattern | {{ text | regex_replace:"/old/":"new" }} |
nl2br |
Line breaks → <br> |
{{ text | nl2br }} |
strip_tags |
Remove HTML tags | {{ html | strip_tags }} |
entities / sanitize |
Escape HTML | {{ input | entities }} |
decode |
Decode HTML entities | {{ input | decode }} |
markdown |
Parse Markdown | {{ content | markdown }} |
wrap |
Wrap in an HTML tag | {{ text | wrap:"span" }} |
surround |
Add text before/after | {{ text | surround:"[":"]" }} |
repeat |
Repeat string | {{ text | repeat:3 }} |
starts_with |
Starts with | {{ text | starts_with:"Hello" }} |
ends_with |
Ends with | {{ text | ends_with:"!" }} |
contains |
Contains substring | {{ text | contains:"word" }} |
length |
String length | {{ text | length }} |
Numeric
| Modifier | Description | Example |
|---|---|---|
add |
Add | {{ price | add:10 }} |
subtract |
Subtract | {{ price | subtract:5 }} |
multiply |
Multiply | {{ price | multiply:1.2 }} |
divide |
Divide | {{ total | divide:100 }} |
mod |
Modulo | {{ n | mod:2 }} |
ceil |
Round up | {{ value | ceil }} |
floor |
Round down | {{ value | floor }} |
round |
Round | {{ value | round:2 }} |
Array
| Modifier | Description | Example |
|---|---|---|
sort |
Sort | {{ items | sort:"name" }} |
reverse |
Reverse | {{ items | reverse }} |
first |
First element | {{ items | first }} |
last |
Last element | {{ items | last }} |
pluck |
Extract a field | {{ users | pluck:"name" }} |
unique |
Unique values | {{ tags | unique }} |
where |
Filter by field | {{ items | where:"status":"active" }} |
chunk |
Split into groups | {{ items | chunk:3 }} |
keys |
Array keys | {{ data | keys }} |
values |
Array values | {{ data | values }} |
count |
Number of items | {{ items | count }} |
join |
Join into a string | {{ tags | join:", " }} |
explode |
Split a string | {{ csv | explode:"," }} |
Date and Time
| Modifier | Description | Example |
|---|---|---|
format |
Format a date | {{ date | format:"d.m.Y" }} |
Current standalone strategy:
- The built-in date/time surface is intentionally minimal and currently limited to
format. formataccepts Unix timestamps and strings that PHP can parse viastrtotime().- If parsing fails, the original string is returned unchanged.
- Carbon is intentionally not a dependency of this project.
- Carbon-style or locale-aware modifiers such as
iso_format,modify_date,days_ago,is_today, ortimezoneare not part of the first stable standalone core. - If richer date/time support is added later, it should be built on native PHP types such as
DateTimeImmutable,DateTimeInterface, andDateTimeZone, preferably as an opt-in extension.
Utilities
| Modifier | Description | Example |
|---|---|---|
is_empty |
Check if empty | {{ items | is_empty }} |
is_array |
Check if value is an array | {{ items | is_array }} |
is_numeric |
Check if value is numeric | {{ value | is_numeric }} |
md5 |
MD5 hash | {{ email | md5 }} |
Extending
Custom Modifier
// Callable $engine->addModifier('money', function(mixed $value, array $params, array $context): string { $currency = $params[0] ?? 'USD'; return number_format((float) $value, 2) . ' ' . $currency; }); // {{ price | money:EUR }} // Class use Bugo\Antlers\Modifiers\ModifierInterface; class ExcerptModifier implements ModifierInterface { public function modify(mixed $value, array $params, array $context): mixed { $length = (int) ($params[0] ?? 150); return mb_substr(strip_tags((string) $value), 0, $length) . '...'; } } $engine->addModifier('excerpt', new ExcerptModifier()); // {{ content | excerpt:200 }}
Custom Tag
Built-in cache/nocache are not part of the required standalone core right now. If you need cache-like behavior, you can add it as a custom extension:
// Callable $engine->addTag('icon', function(array $params): string { $name = $params['name'] ?? ''; return "<svg class=\"icon\"><use href=\"#icon-{$name}\"></use></svg>"; }); // {{ icon name="star" }} // Class with methods (namespace) use Bugo\Antlers\Tags\AbstractTag; class CacheTag extends AbstractTag { public function index(): string|array|null { $key = $this->param('key', 'default'); // ... cache logic return $this->content(); } public function forget(): string|array|null { $key = $this->param('key', 'default'); // ... clear cache return null; } } $engine->addTag('cache', new CacheTag()); // {{ cache key="homepage" }}...{{ /cache }} // {{ cache:forget key="homepage" }}
Paired Tag with Children
$engine->addTag('repeat', function(array $params, array $data, $processor, $method, $children): string { $times = (int) ($params['times'] ?? 1); $output = ''; for ($i = 0; $i < $times; $i++) { $output .= $processor->reduce($children, array_merge($data, ['iteration' => $i + 1])); } return $output; }); // {{ repeat times="3" }}{{ iteration }}. Hello!{{ /repeat }}
Global Variables
$engine->setGlobals([ 'site_name' => 'My Blog', 'year' => date('Y'), 'user' => $currentUser, ]); // Available in all templates without passing them to render() echo $engine->render('© {{ year }} {{ site_name }}');
Strict Mode
$engine->setStrictMode(true); echo $engine->render('{{ name }}', ['name' => 'Alice']); // Alice echo $engine->render('{{ missing }}'); // throws AntlersRuntimeException
By default the engine is lenient: it falls back so a page still renders. Strict mode turns each
of those fallbacks into an AntlersRuntimeException instead:
| Situation | Lenient | Strict |
|---|---|---|
| Undefined variable | '' |
throws |
| Guarded variable, tag or modifier | '' / value unchanged |
throws |
| Unknown tag | '' |
throws |
| Unknown modifier | value unchanged | throws |
{{ loop }} without times/to |
'' |
throws |
{{ scope }} without a name |
'' |
throws |
{{ svg }} without src, or a missing file |
'' |
throws |
{{ partial }} resolving outside the template roots |
'' |
throws |
regex_replace with a failing pattern |
subject unchanged | throws |
Every AntlersRuntimeException carries the templateLine of the statement that failed and
repeats it in the message, so a failure in a long template does not have to be bisected:
$engine->render("<h1>{{ title }}</h1>\n<p>{{ missing }}</p>", ['title' => 'Home']); // throws: Undefined variable: "missing" on line 2
The line is the innermost {{ }} that can be blamed, not the block around it: a failure inside
{{ if }} or a loop body reports its own line.
?? and ??? never throw for an undefined left side, in either mode. The dump tag is not
affected either: an empty result there means debug mode is off, which is a setting rather than
a failure.
Debug Mode
The dump tag stays silent while debug mode is off, so a stray {{ dump }} cannot leak the
template scope in production. Wire it to your own APP_DEBUG equivalent:
$engine->setDebug(true); echo $engine->render('{{ dump }}'); // dumps the current scope echo $engine->render('{{ dump value=user }}'); // dumps a single value
Inside a loop it dumps that iteration's scope. Use force="true" to dump regardless of the setting:
{{ dump force="true" value=user }}
Markdown Renderer
markdown — both the tag and the modifier — is rendered by
league/commonmark, the same parser Statamic uses, so
output matches for templates moved over from Statamic.
Swap in your own renderer by implementing MarkdownRendererInterface:
use Bugo\Antlers\Support\MarkdownRendererInterface; $engine->setMarkdownRenderer(new class implements MarkdownRendererInterface { public function render(string $markdown): string { return my_own_parser($markdown); } });
To keep CommonMark but change its configuration, pass a converter to CommonMarkRenderer:
use Bugo\Antlers\Support\CommonMarkRenderer; use League\CommonMark\CommonMarkConverter; $engine->setMarkdownRenderer(new CommonMarkRenderer( new CommonMarkConverter(['html_input' => 'escape', 'max_nesting_level' => 10]), ));