Liquid - Data Sanitization
Last edit: Oct 26, 2022
When you display data, from user input or from external sources, it is important to sanitize output before displaying it on a website to avoid XSS attacks.
In Liquid on platformOS, we escape every variable output when you use {{ }}
and {% %}
markups.
Input
{% assign user_name = '<a href="https://www.platformos.com">Click Me</a>' %}
<h2>{{ user_name }}</h2>
Output (not processed by browser)
<h2><a href="http://platformos.com">Click Me</a><h1>x</h1></h2>
In this case, HTML tags are not processed by the browser, so the link is not a clickable link.
Disable variable sanitization
In situations when you want to display content as it is, you can use html_safe to specify that this variable can be printed without sanitization.
This is especially important when you try to construct a JSON output.
Input
{% assign color = 'red' %}
{% assign link = '<a href="/car">cars</a>' %}
{
"color": {{ color }},
"link": {{ link | html_safe }}
}
Output
{
"color": red,
"link": <a href="/car">cars</a>
}
Escape variables before passing them to external systems
You can also run HTML/JavaScript sanitization on variables before passing them to tags/filters: