Skip to content

escape

The escape filter is a crucial tool for preventing potential security vulnerabilities and ensuring proper rendering of text content within HTML. It does this by converting characters that have special meaning in HTML (like <, >, &, and ") into their corresponding HTML entities (like &lt;, &gt;, &amp;, and &quot;).

Functionality

  • Strings: Takes a string as input.
  • HTML Encoding: Replaces special characters in the input string with their HTML entity equivalents.
  • Output: Returns a new string with the special characters escaped as HTML entities.

Syntax

    {{ input_string | escape }}

Arguments

The escape filter does not require any arguments.

Code Samples

Example 1: Escaping HTML Tags

    {% assign unsafe_string = "<p>This is a paragraph.</p>" %}

    {{ unsafe_string | escape }}
Output:

    &lt;p&gt;This is a paragraph.&lt;/p&gt;

Example 2: Escaping Special Characters

    {% assign text = "This string contains <, >, and & characters." %}

    {{ text | escape }}
Output:

    This string contains &lt;, &gt;, and &amp; characters.

Example 3: Preventing Cross-Site Scripting (XSS)

    {% assign user_input = "<script>alert('XSS Attack!');</script>" %}

    {{ user_input | escape }}
Output:

    &lt;script&gt;alert('XSS Attack!');&lt;/script&gt;

Outliers and Special Cases

  • Empty Strings: If the input string is empty, the escape filter returns an empty string.
  • Already Escaped Strings: If the input string already contains HTML entities, the escape filter will escape those entities as well, potentially leading to double-escaping issues. To avoid this, consider using the escape_once filter, which escapes a string only once, regardless of whether it has been escaped previously.
  • Non-String Input: If the input is not a string, the filter might attempt to convert it to a string or return an error.

Key Points

  • The escape filter is crucial for preventing cross-site scripting (XSS) vulnerabilities, where malicious code could be injected into your HTML.
  • It is a good practice to always escape any user-generated or untrusted content before rendering it in your templates.
  • For scenarios where you are unsure if the input has already been escaped, the escape_once filter provides a safer option.
  • The filter does not modify the original string; it creates a new, escaped copy.