How to display string that contains HTML in a Twig template?
Want to display unescaped HTML in a Twig template? Use the |raw
filter:
A word to the wise: Always sanitize user-provided HTML content before using the |raw
filter. This is not an optional step, it's a necessity to prevent any potential XSS attacks.
Using the raw filter safely
To safely apply the |raw
filter, sanitize HTML content before rendering it:
The key here is the sanitized_content
— it should be clean of any potential threats, as ready for the spotlight as a well-groomed show dog. Handling this in the back-end preferably before it even reaches your Twig template is the safest approach.
Advanced sanitization with striptags filter
To selectively allow certain HTML tags, Twig provides the |striptags
filter.
It's like a virtual bouncer, allowing only <p>
and <a>
tags into the club, the rest have to stay outside.
Enhanced sanitation using external libraries
Don't trust the content? You can go a step further by using external libraries like HTML Purifier to sanitize the HTML content on your back-end.
And then, in your Twig template, render the clean_html
using the |raw
filter:
Leveraging Symfony's translation feature
For static HTML strings, Symfony's translation feature comes to the rescue. It's like the postal service, delivering your HTML straight into your Twig template from a separate translation file:
In your Twig template, simply use:
What it's really good for: Using raw in practical situations
- Static content: Go ahead, use
|raw
for static strings that are like holy water — untouched by outsider input. - Rich text editors: When rendering content created by codified guardians (trusted admins),
|raw
can come in handy. - Email templates:
|raw
plays a crucial role in ensuring your multi-colored greetings render accurately in various email clients.
Caution - Here be dragons: Considerations when handling dynamic HTML content
- User-generated content: Use
|raw
as you would a raw egg — with utmost care. Unless the content has been sanitized, it is safer to keep the shell on. - Template inheritance: Ensure no unsafe content wormholes its way into your base templates via inclusion.
- Avoiding double-escaping: When you already have PHP functions like
htmlspecialchars
at play,|raw
can be a fickle friend. Steer clear of potential double-escaping issues.
Was this article helpful?