20

I have a field in my settings.html where I am expecting the user to input multiple paragraphs separated by two newline characters. I would like to split this string of input into an array of strings, each representing a paragraph.

I would like to do something like this:

{% assign paragraphs = settings.intro | split: '\n' %}
{% for paragraph in paragraphs %}
    <p>
        {{ paragraph }}
    </p>
{% endfor %}

I can't seem to figure out how to refer to the newline character in Liquid. How can I go about doing this? Is there some kind of work around?

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
ProjectFrank
  • 622
  • 1
  • 6
  • 11

3 Answers3

42

Try this:

{% assign paragraphs = settings.intro | newline_to_br | split: '<br />' %}
{% for paragraph in paragraphs %}<p>{{ paragraph }}</p>{% endfor %}
Josh Brown
  • 3,985
  • 1
  • 20
  • 22
5

If you do, in fact, need Shopify to split by newlines for any reason where you don't iterate with a for loop afterwards, it is indeed possible:

{% assign paragraphs = settings.intro | split: '
' %}
{% for paragraph in paragraphs %}
    <p>
        {{ paragraph }}
    </p>
{% endfor %}

ie. you need to type an explicit newline into your source code.

This is due to the way Liquid works, quoting from the documentation about Types:

Liquid does not convert escape sequences into special characters.

morganbaz
  • 2,997
  • 1
  • 17
  • 30
  • OMG how crazy is that. It works, thanks a lot for the hint and great that you found out! – Cenco May 15 '23 at 14:20
4

@josh-browns answer got me pretty much there and might be enough for most instances. However, I had some blank paragraphs coming through from user generated double lines.

Denilson Sá Maia comment of strip_newlines did not help with my markdown processor so I checked if each line was empty manually before outputting the paragraph.

{% for paragraph in paragraphs %}
    {% assign paragraph-length = paragraph | number_of_words %}
    {% if paragraph-length > 0 %}
        <p>{{ paragraph }}</p>
        IMAGE HERE
    {% endif %}
{% endfor %}

This doesn't solve the blanks in the array, for that I iterated over the array to create a new one, with only valid content. It would be really nice if there was a filter that worked on arrays, not just hashes.

{% assign all-paragraphs = content  | strip | newline_to_br | strip_newlines | split: "<br />"  %}
{% assign paragraphs = site.emptyArray  %}
{% for paragraph in all-paragraphs %}
    {% if paragraph and paragraph != "" and paragraph != site.emptyArray %}
         {% assign paragraphs = paragraphs | push: paragraph %}
    {% endif %}
{% endfor %}
Craig.C
  • 561
  • 4
  • 17