Resources »

Solutions Hub »

Automations »

Trim whitespace in scripting tags

Using tag modifiers

Adding a dash - to opening or closing scripting tags will trim leading or trailing whitespace.

  • start:
      return:
        output@text:
          This text
          
          {{-" has no leading or trailing whitespace "-}}
          
          in it.
  • __return:
      output: This text has no leading or trailing whitespace in it.

Using |spaceless filter

The |spaceless filter removes whitespace between HTML tags in literal text typed into the template.

It does not work on a placeholder. Add |raw first, as in {{html|raw|spaceless}}, or use apply spaceless instead. Without that, the filter returns the markup HTML-escaped with its whitespace intact, and reports no error.

  • start:
      return:
        output@text: 
          {{
            "<div>
              <p>This has extra space</p>
              <p>between tags</p>
            </div>"|spaceless
          }}
  • __return:
      output: <div><p>This has extra space</p><p>between tags</p></div>

Using apply spaceless

For larger blocks of HTML, and for any markup that contains placeholders, use {% apply spaceless %}. This is the reliable form in an automation, where the content is usually in a placeholder rather than typed into the template.

  • start:
      return:
        output@text:
          {% apply spaceless %}
          <div>
            <span>This will all be on a single line.</span>
          </div>
          {% endapply %}
  • __return:
      output: <div><span>This will all be on a single line.</span></div>