Skip to content

escape_once

The escape_once filter is designed to ensure that a string is HTML-escaped exactly once, even if it has been escaped previously. This is useful in scenarios where you might be dealing with text that has already been escaped and you want to avoid double-escaping, which could lead to the display of encoded characters rather than the intended text.

Functionality

  • Strings: Takes a string as input.
  • Escaping: Escapes HTML characters (e.g., <, >, &, ") by replacing them with their corresponding HTML entities (e.g., &lt;, &gt;, &amp;, &quot;).
  • Single Escaping: Ensures that the escaping process happens only once by first decoding any existing HTML entities and then re-encoding them.
  • Output: Returns a new string with HTML entities ensuring only a single escape.

Syntax

    {{ input_string | escape_once }}

Arguments

The escape_once filter does not require any arguments.

Code Samples

Example 1: Avoiding Double Escaping

    {% assign escaped_text = "&lt;p&gt;This text is already escaped.&lt;/p&gt;" %}

    {{ escaped_text | escape_once }}

Output:

    <p>This text is already escaped.</p>

Example 2: Escaping Potentially Unsafe Input

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

    {{ user_input | escape_once }}

Output:

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

Outliers and Special Cases

  • Empty Strings: If the input string is empty, the escape_once filter returns an empty string.
  • Non-String Input: If the input is not a string, the filter might attempt to convert it to a string or return an error, depending on how Experience Builder handles type conversions.

Key Points

  • The escape_once filter is essential for preventing double-escaping issues, which can lead to broken HTML and potential security vulnerabilities (like cross-site scripting or XSS attacks).
  • It is particularly useful when you are working with content that might have already been escaped or when you are unsure if the input has been escaped before.
  • Use this filter judiciously. For normal string input that has not been escaped, use the escape filter directly.