Home > Shopify Development > How to strip whitespace from the left or right side in Liquid

How to strip whitespace from the left or right side in Liquid in Shopify in Shopify

Sam Nguyen
Sam Updated: June 26, 2024

Share:

Drive 20-40% of your revenue with Avada
avada email marketing

Liquid template is usually used by website developers because it is compatible with Shopify. In previous tutorials, you have already known about types, operators, trusty and falsy. Today tutorial focuses on whitespace control and presents codes to strip whitespace from the left or right side in Liquid.

Table of content

What is whitespace control

Liquid is a website language for Shopify platform. In computer programing, white space is any character or series of characters that represent horizontal or vertical space in typography. When rendered, a whitespace character is not compatible with a visible mark, but typically does occupy an area on a page.

Code to strip whitespace from the left or right side in Liquid

In Liquid, we can use a hyphen in your tag syntax namely percentage, curly brackets to strip whitespace from a rendered tag’s left or right side.

In general, in case it does not include output text, any line of Liquid in your template still produce a back line in your rendered HTML. For instance, you can leave a blank space in front of “tomato”

Input


{% assign my_variable = "tomato" %}
{{ my_variable }}

Output



tomato

If you do not want to show the blank space, you include hyphens in assign tag. Look at the sample:

Input


{%- assign my_variable = "tomato" -%}
{{ my_variable }}

Output


tomato

In a more complex situation, if you do not want any of your tags to output whitespace, you can add hyphens to both sides of all your tags as a general rule. For example, you would like to present a long name and a slogan without whitespace.

Input


{%- assign username = "John G. Chalmers-Smith" -%}
{%- if username and username.size > 10 -%}
  Wow, {{ username }}, you have a long name!
{%- else -%}
  Hello there!
{%- endif -%}

Output


Wow, John G. Chalmers-Smith, you have a long name!

Conclusion

To sum up, this tutorial aims to guide you to remove whitespace from the left or right side in Liquid. Eliminating whitespace will help you to generate a better interface with customers. We hope that you will find something interesting for your website. If you have any difficulties, let us know and we will assist you.


Sam Nguyen is the CEO and founder of Avada Commerce, an e-commerce solution provider headquartered in Singapore. He is an expert on the Shopify e-commerce platform for online stores and retail point-of-sale systems. Sam loves talking about e-commerce and he aims to help over a million online businesses grow and thrive.

Stay in the know

Get special offers on the latest news from AVADA.