Homepage

Liquid - Data Sanitization

Last edit: Jan 31, 2024

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 {% echo %} tag. markups.

Input


{% assign user_name = '<a href="https://www.platformos.com">Click Me</a>' %}

<h2>{{ user_name }}</h2>

Output (not processed by browser)



<h2>&lt;a href="http://platformos.com"&gt;Click Me&lt;/a&gt;&lt;h1&gt;x&lt;/h1&gt;</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 filter to mark variable as safe and bypass sanitization.

Input


{% assign link = '<a href="/car">cars</a>' %}
{{ link | html_safe }}

The above code will generate a clickable link.

The previous method marks the whole variable as safe to be printed, but it might not be the case - for example, you might want to store in a variable safe and unsafe part at the same time. In this scenario, the print tag will work as expected:

Input


{% liquid
  assign invokable_script = "<script>alert('I will be executed')</script>"
  assign malicious_script = "<script>alert('I should be escaped')</script>"
%}
{% capture result %}
  {{ malicious_script }}{{ invokable_script | html_safe }}
{% endcapture %}
{% print result %}

The "I will be executed" alert will appear on page load, but "I should be escaped" will not be evaluated and will be rendered inline.

Escape variables before passing them to external systems

You can also run HTML/JavaScript sanitization on variables before passing them to tags/filters:

Questions?

We are always happy to help with any questions you may have.

contact us