Twig and untrusted text: handling HTML, links and quotations
Separate plain text from editorial HTML in an independent Symfony example: explicit tag, attribute and link policies, literal quotations and response structure checks.
A note title contains <strong>, an author pastes an HTML fragment into a quotation, and an editor returns a few paragraphs with links. In storage, these may be three strings of the same type. On a page, they have different permissions: the title and quotation display text, while the article body permits some markup.
The /text-boundary page displays fixed strings and reads neither a database nor network sources. The shared article_demo application already has forms and a MySQL 8.4/InnoDB store accessed through native PDO; this exercise preserves them and requires no schema initialization. Install the public symfony/html-sanitizer package through Composer/Flex and add a separate policy.
The earlier article about an author's journal as a product discussed an editorial package and its path to publication. Here I focus on a smaller boundary: what the browser receives in place of a string from storage. Having an editor or a known author does not define that boundary by itself.
Three fields, three agreements
First decide what a user may provide, then choose the filter.
| Field | Intended result | Rule in this example |
|---|---|---|
| Title | Literal characters, including angle brackets | HTML escaping |
| Quotation containing code | Text that can be read and copied | HTML escaping |
| Editorial body | Paragraphs, emphasis, lists and links | A narrow set of permitted HTML |
Escaping changes how characters are represented in HTML. Sanitization parses markup and builds a permitted result. Symfony describes HTML Sanitizer as processing untrusted HTML. In this example, only the third field needs it. Applying it to a title could turn some entered characters into markup or remove them, even though the reader expected literal text.
For ordinary text, use automatic escaping. Twig lets a template state the HTML strategy explicitly. This makes the agreement visible next to the output.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ title }}</title>
</head>
<body>
{% autoescape 'html' %}
<main>
<h1 id="note-title">{{ title }}</h1>
<blockquote id="plain-quote">{{ quote }}</blockquote>
<section id="note-body" aria-label="Note body">
{{ body|sanitize_html('app.note_body') }}
</section>
</main>
{% endautoescape %}
</body>
</html>
Seeing <strong> on screen in this field is not a formatting failure. It is the intended behavior of a text field. Adding raw would change it: that filter marks a value as safe for Twig, but does not inspect the HTML. Naming a variable safeHtml does not inspect anything either.
The next step in the shared project
Continue the same Symfony project, article_demo, created from the official skeleton in the earlier articles. Run commands from its root. Add the required dependencies and files while preserving earlier routes, services and data. PHP 8.4+, Symfony 8.1 and Composer 2 remain the example requirements.
php --version
composer --version
composer require 'symfony/twig-bundle:8.1.*' 'symfony/html-sanitizer:8.1.*' --no-interaction
composer require --dev symfony/test-pack --no-interaction
mkdir -p src/Controller templates/text_boundary tests/Controller config/packages
Body permissions should be explicit
Create config/packages/html_sanitizer.yaml:
framework:
html_sanitizer:
sanitizers:
app.note_body:
default_action: 'drop'
allow_safe_elements: false
allow_static_elements: false
allow_elements:
p: []
strong: []
em: []
blockquote: []
code: []
pre: []
ul: []
ol: []
li: []
br: []
a: ['href', 'title']
block_elements: ['div', 'span']
drop_elements: ['script', 'style', 'iframe', 'object', 'embed', 'svg', 'math', 'form', 'img', 'template', 'figure']
allowed_link_schemes: ['https']
allow_relative_links: false
force_attributes:
a:
rel: 'noopener noreferrer'
max_input_length: 20000
This is a deliberately limited vocabulary for a short note. Each allowed tag has its own attribute list. An a element retains href and title; class, style, event handlers and an arbitrary target are outside this agreement. Both broad baseline sets are disabled so that a future extension of the permissions is a visible configuration change.
There is also a difference between an unnecessary wrapper and a subtree that should not appear at all. For div and span, this exercise keeps their processed contents. It removes figure and the listed active structures along with their contents. Other unspecified elements follow default_action: drop. This can remove useful content from an unfamiliar format, so an author needs a preview before saving a large document.
The parameter names and the meanings of allow_elements, block_elements, drop_elements and default_action are described in the Symfony configuration reference. Our choices are not a universal policy for every editor. If tables or images are required, define their behavior separately and add corresponding checks.
The max_input_length: 20000 boundary belongs to this lab configuration. It does not define how an HTTP form should explain an oversized document to its user. Real input needs a separate request limit and an agreed response when it is exceeded; the presence of a sanitizer is not a promise that every character will be preserved.
The controller passes data; the template applies the rule
Create src/Controller/TextBoundaryController.php:
<?php
declare(strict_types=1);
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
final class TextBoundaryController extends AbstractController
{
#[Route('/text-boundary', name: 'app_text_boundary', methods: ['GET'])]
public function __invoke(): Response
{
return $this->render('text_boundary/index.html.twig', [
'title' => '<strong>Notes & examples</strong>',
'quote' => '"><img src=x onerror=alert(1)>',
'body' => <<<'HTML'
<div><p>Hello <strong>reader</strong>.</p>
<blockquote>A quote with <em>emphasis</em>.</blockquote>
<p><a href="https://example.org/notes?a=1&b=2" title="Reference" onclick="alert(1)">Reference</a></p>
<p><a href="javascript:alert(1)">Unapproved URL</a></p>
<script>alert(1)</script><img src=x onerror=alert(1)></div>
HTML,
]);
}
}
Add the controller registration below to the existing services block in config/services.yaml. Preserve all other services and imports; this extends the shared application’s explicit configuration.
services:
App\Controller\TextBoundaryController: ~
In the first field, the HTML resembles intentional emphasis. The second contains a synthetic event-handler attribute. The third mixes allowed elements, an HTTPS link and structures that should disappear. This is a deliberate fixture for a local check, not material copied from a real attack.
Create templates/text_boundary/index.html.twig:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ title }}</title>
</head>
<body>
{% autoescape 'html' %}
<main>
<h1 id="note-title">{{ title }}</h1>
<blockquote id="plain-quote">{{ quote }}</blockquote>
<section id="note-body" aria-label="Note body">
{{ body|sanitize_html('app.note_body') }}
</section>
</main>
{% endautoescape %}
</body>
</html>
The body uses Symfony's sanitize_html filter with the explicit name app.note_body. No extra raw is required. The title and quotation do not pass through the sanitizer, so they remain text. The template has no branch that disables escaping for an author with a particular status.
Do not append new untrusted markup after sanitization. Otherwise, the inspected fragment and the appended input have different origins, while the browser receives their combination. A title displayed alongside the body should remain a separate escaped variable.
A link needs more than escaped quotation marks
HTML escaping helps keep a value inside a quoted attribute, but does not choose an allowed URL scheme. The string javascript:alert(1) may contain no characters that require conversion to HTML entities. Our href policy therefore permits only https and disables relative URLs separately.
Under this policy, a disallowed address should lose its href while the link label remains readable. An http link is rejected too: this example does not automatically “repair” it. The application sets rel, and an arbitrary target is discarded. However, HTTPS says nothing about the honesty or usefulness of the destination page. Reviewing an editorial source remains a separate task.
Output context matters as well. Twig documentation distinguishes HTML, JavaScript, CSS and URL component contexts. This sanitizer's result is intended for the body of an HTML page. It must not automatically be reused inside a JavaScript string, CSS or an unchecked attribute. OWASP explains why protection depends on the insertion context.
Quoted code should stay quoted
When I explain an <a> tag to a reader, it should not turn into an actual link. A text field is sufficient for a short quotation, as in our blockquote. For multiline code, an escaped variable can sit inside static pre and code elements. Its characters do not become browser instructions.
Replacing the sanitizer with strip_tags and a few allowed tags would be a different design with different properties. PHP explicitly warns that the function is not an XSS defense and does not clean attributes on allowed tags. We need policies for elements, attributes and URLs, so removing tag names alone is insufficient.
Check both wanted and unwanted behavior
Removing everything is easy, but the note would lose its value. A check must establish both that forbidden structures do not reach the relevant HTML and that permitted content remains available to the reader.
Create tests/Controller/TextBoundaryTest.php:
<?php
declare(strict_types=1);
namespace App\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DomCrawler\Crawler;
use Twig\Environment;
final class TextBoundaryTest extends WebTestCase
{
public function testPlainTextKeepsCharactersWithoutCreatingElements(): void
{
$title = '<strong>A&B</strong>';
$quote = '"><img src=x onerror=alert(1)>';
$page = $this->renderPage('', $title, $quote);
self::assertSame($title, $page->filter('#note-title')->text());
self::assertSame($quote, $page->filter('#plain-quote')->text());
self::assertCount(0, $page->filter('#note-title strong, #plain-quote img'));
}
public function testEditorialMarkupAndHttpsLinkAreRetained(): void
{
$page = $this->renderPage(
'<p>Hello <strong>reader</strong>.</p>'
.'<blockquote><em>Quote</em></blockquote><pre><code>x < y</code></pre>'
.'<ul><li>One</li></ul>'
.'<a href="https://example.org/notes?a=1&b=2" title="Reference">Read</a>'
);
$body = $page->filter('#note-body');
self::assertSame('reader', $body->filter('strong')->text());
self::assertSame('Quote', $body->filter('blockquote em')->text());
self::assertSame('x < y', $body->filter('pre code')->text());
self::assertSame('One', $body->filter('ul li')->text());
self::assertSame('https://example.org/notes?a=1&b=2', $body->filter('a')->attr('href'));
self::assertSame('Reference', $body->filter('a')->attr('title'));
}
public function testActiveAndEmbeddedContentIsDropped(): void
{
$page = $this->renderPage(
'<p>Keep</p><script>SCRIPT_MARKER</script><style>STYLE_MARKER</style>'
.'<iframe>FRAME_MARKER</iframe><svg><text>SVG_MARKER</text></svg>'
.'<img src=x onerror=alert(1)><form>FORM_MARKER</form>'
);
$body = $page->filter('#note-body');
self::assertCount(0, $body->filter('script, style, iframe, svg, img, form'));
self::assertSame('Keep', $body->text());
}
public function testUnapprovedUrlsLoseTheirHrefButKeepTheLabel(): void
{
foreach ([
'javascript:alert(1)',
'JaVaScRiPt:alert(1)',
'javascript:alert(1)',
'data:text/html,blocked',
'http://example.org/notes',
'/notes',
'//example.org/notes',
'#part',
] as $url) {
$page = $this->renderPage('<p><a href="'.$url.'">Label</a></p>');
$body = $page->filter('#note-body');
self::assertCount(0, $body->filter('a[href]'), $url);
self::assertSame('Label', $body->text(), $url);
}
}
public function testAttributesFollowTheSamePolicy(): void
{
$page = $this->renderPage(
'<p class="overlay" style="position:fixed" onclick="alert(1)">Text</p>'
.'<a href="https://example.org/" target="_blank" rel="opener" onmouseover="alert(1)">Link</a>'
);
$body = $page->filter('#note-body');
self::assertCount(0, $body->filter('[class], [style], [onclick], [target], [onmouseover]'));
self::assertSame('noopener noreferrer', $body->filter('a')->attr('rel'));
}
public function testBlockedWrappersAndDroppedSubtreesAreDifferent(): void
{
$page = $this->renderPage(
'<div><p>A <span><em>B</em></span></p></div>'
.'<figure><p>DROP_MARKER</p></figure>'
);
$body = $page->filter('#note-body');
self::assertCount(0, $body->filter('div, span, figure'));
self::assertSame('B', $body->filter('p em')->text());
self::assertSame('A B', $body->text());
}
public function testEmptyBodyStaysEmpty(): void
{
$page = $this->renderPage('');
self::assertSame('', $page->filter('#note-body')->text());
self::assertCount(0, $page->filter('#note-body *'));
}
public function testHttpPageUsesTheConfiguredBoundary(): void
{
$client = self::createClient();
$client->request('GET', '/text-boundary');
self::assertResponseIsSuccessful();
self::assertSelectorTextContains('#note-title', '<strong>Notes & examples</strong>');
self::assertSelectorNotExists('#note-title strong');
self::assertSelectorNotExists('#plain-quote img');
self::assertSelectorTextContains('#note-body strong', 'reader');
self::assertSelectorExists('#note-body a[href="https://example.org/notes?a=1&b=2"]');
self::assertSelectorNotExists('#note-body script, #note-body img, #note-body [onclick]');
self::assertSelectorNotExists('#note-body a[href^="javascript:"]');
}
private function renderPage(string $body, string $title = 'Example', string $quote = 'Example quote'): Crawler
{
self::bootKernel();
$twig = self::getContainer()->get(Environment::class);
$html = $twig->render('text_boundary/index.html.twig', [
'title' => $title,
'quote' => $quote,
'body' => $body,
]);
return new Crawler($html);
}
}
The file contains 8 test methods. One method exercises 8 URL variants, including mixed case and an HTML entity inside the scheme name. The assertions inspect DOM structure, not merely the absence of the word script in a string: that word can legitimately appear in a plain-text quotation.
Symfony WebTestCase checks the application's response here. DomCrawler does not execute JavaScript, so this does not replace viewing the page in a browser. Separately confirm that the title and quotation remain literal, allowed text is preserved, and unwanted elements are absent.
composer check-platform-reqs
find src tests -name '*.php' -print0 | xargs -0 -n1 php -l
php bin/console lint:yaml config/packages/html_sanitizer.yaml
php bin/console lint:twig templates/text_boundary
php bin/console lint:container --env=test
APP_ENV=test php bin/phpunit tests/Controller/TextBoundaryTest.php --testdox
Run these commands on the final files. The expected result is successful checks of literal text, permitted markup, URL policy and the HTTP page. Until execution occurs, these remain acceptance conditions.
| Input | What should appear |
|---|---|
<strong>A&B</strong> in the title |
Literal text with brackets, without a strong element |
strong in the editorial body |
Allowed emphasis |
script or img in the body |
Neither element |
| A forbidden URL scheme | A link label without href |
div / span around permitted text |
Processed content without the wrappers |
| An empty body | An empty section with no added text |
The rule should survive an editor change
For this exercise, I apply the policy when rendering. A larger editorial product could retain a source document and a derived sanitized representation, but it would then need to record which policy version produced that representation. Otherwise, changing the allowlist could leave older articles with the previous behavior.
Keeping the original does not make it suitable for direct output. A preview, main page, search excerpt and notification each have their own insertion contexts. Each needs a deliberate agreement about text or markup.
The useful outcome of this design is explicit responsibility for each field. A title does not acquire HTML permissions by accident, a quotation does not execute its own example, and the editorial body has a small, testable set of permissions. Extend those permissions together with an explanation of the need and checks of the resulting behavior.