Whitespace control

Every line of code in a Liquid template produces an LF character at the end of a line. This applies also to lines that don't produce any text.

Controlling whitespace characters, especially newline characters, is crucial in the CSV format.

You can include a hyphen in your tag syntax {{-, -}}, {%-, and -%} to strip whitespace from the left or right side of a rendered tag.

Placing a hyphen in the opening tag {{- or {%- removes also a newline character at the one of a previous line.

For example:

Liquid Code
{% for item in order.line_items %}
{{ item.title }}
{% endfor %}

produces the following output (assuming that the order contains two line items, a Cap and a T-Shirt):

Output

Cap

T-Shirt

Add hyphens to the for-loop tags will remove the empty lines.

Liquid Code
{%- foritem in order.line_items %}
{{ item.title }}
{%- endfor %}
Output
T-Shirt
Cap

You could place hyphens at the end of the control tags as well to get the same result.

Liquid Code
{% for item in order.line_items -%}
{{ item.title }}
{% endfor -%}

However, adding hyphens at both sides of the for-loop tags would also remove line separators between subsequent items reducing the output to one line.

Liquid Code
{%- for item in order.line_items -%}
{{ item.title }}
{%- endfor -%}
Output
T-ShirtCap

Last updated