How to split a string by newline in shopify?

Member

by larissa , in category: PHP General , 4 months ago

How to split a string by newline in shopify?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 4 months ago

@larissa 

In Shopify, you can split a string by newline using the split filter provided by Liquid, the templating language used in Shopify.


To split a string by newline, you can make use of the following code:

1
2
{% assign lines = your_string | split: '
' %}


Explanation:

  • your_string is the variable or string that you want to split.
  • split is the Liquid filter used to split the string.
  • ' ' is the delimiter used to split the string by newline. The backslash is used to escape the special character n, representing a newline.


After splitting the string, you can access the individual lines using lines[0], lines[1], and so on.


Example usage: Let's say you have a string that contains multiple lines, stored in the variable content. If you want to split it into individual lines and loop through them, you can do the following:

1
2
3
4
5
6
7
8
9
{% assign content = "Line 1
Line 2
Line 3" %}
{% assign lines = content | split: '
' %}

{% for line in lines %}
  <p>{{ line }}</p>
{% endfor %}


This code will:



Note: The split filter is available in the newer Shopify themes. If you are using an older theme, you may need to upgrade or check the Liquid version in use.