The Analogy: The Print Shop's Pre-Printed Letterhead
A busy print shop does not design each letter from scratch. It keeps a stack of pre-printed letterhead: the company logo, the address, the footer, all already on the page, with a blank space in the middle where the day's message goes. The clerk takes a sheet of letterhead and types only the variable part -- the recipient, the body -- into the empty space. The fixed frame is printed once and reused for every letter; only the contents change. A template engine is that letterhead. Blade, Laravel's engine, lets you write the fixed HTML frame once and drop the variable data into marked slots.
The print shop has an ironclad rule for the variable space: anything a customer hands in to be inserted is treated as plain text, never as a printing instruction. If a customer's message happens to contain what looks like a typesetting command, the clerk prints those characters literally rather than obeying them. This is escaping, and it is the single most important safety property of a template engine. Blade's {{ }} automatically escapes inserted values, so a user's data cannot smuggle live HTML or script into the page. The letterhead's frame is trusted; the customer's message never is.
Occasionally the shop does need to insert genuinely pre-approved formatted content -- a block of the company's own designed graphics, say -- into the variable space as-is. For that there is a separate, explicit process, clearly distinct from the ordinary "just print the text" path, so no one confuses trusted content with customer input. Blade marks this with {!! !!}, raw output, which is deliberately more awkward to type precisely because it should be rare and considered.
The failure mode is the clerk who, to save a step, starts obeying whatever typesetting-looking characters appear in customer messages. Now a customer who writes the right sequence can change the letterhead, insert their own graphics, or hijack the layout of every letter. On the web this is cross-site scripting: the moment user data is inserted without escaping, an attacker's <script> runs in every visitor's browser. The template engine's escaping is the guardrail; the developer who reaches for raw output out of habit, or who builds HTML by string concatenation instead of using the escaped slots, tears the guardrail down. The frame is only safe while the variable space stays strictly text.
Syntax or Core Structure
These plain-PHP renderers illustrate Blade's behaviour without the framework. The defining feature is that the ordinary interpolation slot escapes HTML, while a separate raw slot does not. Here {{ var }} escapes and {!! var !!} passes through.
<?php
declare(strict_types=1);
function render(string $template, array $data): string {
$out = preg_replace_callback('#\{!!\s*(\w+)\s*!!\}#', function ($m) use ($data) {
return (string) ($data[$m[1]] ?? '');
}, $template);
$out = preg_replace_callback('#\{\{\s*(\w+)\s*\}\}#', function ($m) use ($data) {
return htmlspecialchars((string) ($data[$m[1]] ?? ''), ENT_QUOTES);
}, $out);
return $out;
}
$data = [
'name' => '<b>Ada</b>',
'raw' => '<i>trusted</i>',
];
echo render('Hello {{ name }}', $data), "\n";
echo render('Raw: {!! raw !!}', $data), "\n";
echo render('Missing: [{{ nope }}]', $data), "\n";
Output:
Hello <b>Ada</b>
Raw: <i>trusted</i>
Missing: []
The {{ name }} slot runs htmlspecialchars, so the <b> tags in Ada's name become <b> -- displayed as text, not rendered as bold. The {!! raw !!} slot passes its trusted content straight through, keeping the <i> live. A missing key yields an empty string rather than an error. This escape-by-default, raw-by-exception behaviour is exactly Blade's {{ }} versus {!! !!}, and it is what makes the default safe.
Technical Depth: Directives, Layouts, and Loops
Blade's directive vocabulary
Blade adds directives -- @-prefixed keywords -- for the control flow a template needs, compiling them to plain PHP behind the scenes. The common ones map directly onto PHP constructs.
| Directive | Compiles to | Purpose |
|---|---|---|
{{ $x }} | escaped echo | Safe output |
{!! $x !!} | raw echo | Trusted HTML only |
@if / @endif | if | Conditional markup |
@foreach / @endforeach | foreach | Repeating markup |
@yield(name) | insert a section | Layout slots |
@section / @endsection | define a section | Child content |
Layout inheritance
The signature feature of a template engine is layout inheritance: a parent layout defines the page frame with named slots, and child views fill those slots. This models Blade's @yield in the layout and @section in the child.
<?php
declare(strict_types=1);
final class View {
private array $sections = [];
public function section(string $name, string $content): void {
$this->sections[$name] = $content;
}
public function renderLayout(string $layout): string {
return preg_replace_callback('#@yield\(\s*(\w+)\s*\)#', function ($m) {
return $this->sections[$m[1]] ?? '';
}, $layout);
}
}
$layout = "<html><head><title>@yield(title)</title></head>"
. "<body>@yield(body)</body></html>";
$v = new View();
$v->section('title', 'Home');
$v->section('body', 'Welcome');
echo $v->renderLayout($layout), "\n";
Output:
<html><head><title>Home</title></head><body>Welcome</body></html>
The layout declares two slots, @yield(title) and @yield(body). The view supplies both sections, and renderLayout replaces each yield with its section content. Blade writes this as a child view with @extends('layout') and @section('title', 'Home'), but the mechanism -- a frame with slots that children fill -- is identical, and it is what lets every page share one header and footer.
Loops with escaping
Rendering a list means repeating a row template per item, and every value inserted must still be escaped. This is Blade's @foreach combined with {{ }}.
<?php
declare(strict_types=1);
function renderList(string $rowTemplate, array $items): string {
$out = '';
foreach ($items as $item) {
$out .= preg_replace_callback('#\{\{\s*(\w+)\s*\}\}#', function ($m) use ($item) {
return htmlspecialchars((string) ($item[$m[1]] ?? ''), ENT_QUOTES);
}, $rowTemplate);
}
return $out;
}
$items = [
['name' => 'Ada', 'role' => 'Admin'],
['name' => 'Ben', 'role' => 'User'],
['name' => '<x>', 'role' => 'User'],
];
echo renderList("- {{ name }} ({{ role }})\n", $items);
Output:
- Ada (Admin)
- Ben (User)
- <x> (User)
Each item renders the row template with its values escaped, so the third item's <x> name is safely shown as <x>. Escaping applies inside loops exactly as outside them -- a common place developers forget, assuming list data is somehow safer than a single value. It is not: every inserted value is untrusted until escaped.
Reusable components
A component is a small, self-contained template rendered with its own set of properties and embedded wherever it is needed -- an alert box, a card, a button. Defining the markup once and passing different properties keeps the UI consistent and the templates dry.
<?php
declare(strict_types=1);
function component(string $template, array $props): string {
return preg_replace_callback('#\{\{\s*(\w+)\s*\}\}#', function ($m) use ($props) {
return htmlspecialchars((string) ($props[$m[1]] ?? ''), ENT_QUOTES);
}, $template);
}
$alert = '<div class="alert alert-{{ type }}">{{ message }}</div>';
echo component($alert, ['type' => 'error', 'message' => 'Save failed']), "\n";
echo component($alert, ['type' => 'ok', 'message' => 'Saved <b>ok</b>']), "\n";
Output:
<div class="alert alert-error">Save failed</div>
<div class="alert alert-ok">Saved <b>ok</b></div>
The one $alert template renders twice with different properties, producing an error and an ok alert from the same markup. The escaping still applies, so the second message's <b> is neutralised to <b> rather than rendered. Blade formalises this as components -- <x-alert type="error" message="..."/> -- with their own classes and slots, but the principle is the same: parameterised, reusable, escaped fragments.
Real World Example: A Page That Renders Untrusted Comments Safely
The real test of a template engine is a page that mixes trusted layout with untrusted user content. Here a layout has a variable title, a pre-built trusted sidebar section, and a user-submitted comment that contains an XSS payload. The escaped slot neutralises the attack automatically.
<?php
declare(strict_types=1);
final class Template {
private array $sections = [];
public function set(string $name, string $value): void {
$this->sections[$name] = $value;
}
public function render(string $layout, array $vars): string {
$out = preg_replace_callback('#\{\{\s*(\w+)\s*\}\}#', function ($m) use ($vars) {
return htmlspecialchars((string) ($vars[$m[1]] ?? ''), ENT_QUOTES);
}, $layout);
return preg_replace_callback('#@yield\(\s*(\w+)\s*\)#', function ($m) {
return $this->sections[$m[1]] ?? '';
}, $out);
}
}
$comment = '<script>steal()</script> nice post';
$t = new Template();
$t->set('sidebar', '<nav>Home</nav>');
$layout = "<h1>{{ title }}</h1>"
. "<aside>@yield(sidebar)</aside>"
. "<p>{{ comment }}</p>";
$html = $t->render($layout, [
'title' => 'Post',
'comment' => $comment,
]);
echo $html, "\n";
Output:
<h1>Post</h1><aside><nav>Home</nav></aside><p><script>steal()</script> nice post</p>
The title and comment go through the escaped {{ }} slot, while the trusted sidebar is inserted through the @yield section. The user's comment contained <script>steal()</script>, but escaping turned it into <script>...</script>, which the browser shows as harmless text rather than executing. The trusted <nav> sidebar, inserted as a section, stays live because it is application-controlled markup, not user input. This is the correct split: layout and trusted fragments are raw, user data is always escaped.
The design flaw is that the trusted-versus-untrusted distinction here rests entirely on developer discipline about which channel a value travels through, with nothing enforcing it. The sections mechanism inserts its content raw, so if a developer ever routes user input through set() instead of the escaped vars -- an easy mistake when a "sidebar" later includes a user's display name -- the XSS protection silently evaporates for that value, and nothing in the code or the output warns of it. The engine makes the safe path the default for {{ }}, but it cannot know that a given section string is trusted; it simply trusts whatever reaches the raw channel. Real Blade has the same fundamental exposure with {!! !!} and with HTML built in components, which is why defence in depth matters: a Content-Security-Policy header, sanitising rich user HTML through a dedicated library before it ever becomes a "trusted" fragment, and code review that treats every raw-output site as a red flag. Escaping-by-default stops the common case, but a template engine cannot by itself guarantee that a human never hands it poison through the trusted door.
Common Mistakes
- Reaching for raw output out of habit. Using
{!! !!}when{{ }}would do reopens XSS. Default to escaped output; use raw only for genuinely trusted, pre-sanitised HTML.
- Assuming loop data is safe. Forgetting to escape values inside a
@foreachis a classic hole. Every inserted value is untrusted, in loops as much as anywhere.
- Building HTML by string concatenation. Hand-gluing user data into HTML strings bypasses the engine's escaping entirely. Render through the template so escaping applies.
- Putting logic in templates. Heavy computation or queries in a view mixes concerns and hurts performance. Prepare data in the controller and pass it in ready to display.
- Trusting a "trusted" fragment forever. A section that starts as static markup may later include user data. Re-examine any raw-output channel whenever its content source changes.
- Double-escaping. Escaping a value yourself and then passing it through an escaping slot yields
&lt;. Let the engine escape once; do not pre-escape.
- Escaping for the wrong context. HTML-escaping a value placed into a JavaScript or URL context is insufficient. Match the escaping to where the value lands.
- Forgetting the attribute context. Inserting an unquoted value into an HTML attribute can break out of it. Quote attributes and escape for the attribute context.
- Disabling escaping globally. Turning off auto-escaping to fix one stubborn case removes protection everywhere. Fix the single case with a considered raw output instead.
Best Practices
- Use the escaped output slot by default, treating raw output as a rare, deliberate exception for trusted content only.
- Escape every user-supplied value, including those rendered inside loops, since list data is no safer than a single value.
- Keep templates focused on presentation: prepare and shape data in the controller, and pass it in ready to display.
- Re-audit any raw-output or "trusted section" channel whenever the source of its content changes, since trust can quietly erode.
- Match escaping to context -- HTML, attribute, JavaScript, URL -- rather than assuming HTML-escaping covers every case.
- Sanitise rich user HTML through a dedicated library before treating it as trusted, never by hand.
- Add defence in depth such as a Content-Security-Policy header, so a single missed escape is not automatically exploitable.
- Share one layout with named slots across pages, keeping the frame consistent and the per-page content minimal.
Practice Exercises
- Write a
renderfunction supporting an escaped{{ }}slot and a raw{!! !!}slot, and demonstrate that a value containing<b>is escaped in one and passed through in the other.
- Build a layout with two
@yieldslots and a view that fills both, then render the combined page and confirm the frame surrounds the section content.
- Render a list of items with a row template, deliberately include an item whose value contains
<script>, and show that it is escaped in the output.
- Assemble a page mixing a trusted section and an escaped user comment containing an XSS payload, and prove the payload is neutralised while the trusted markup stays live.