d
Topic
Posts:
5829
Last edited December 06, 2008

Doing a split with Liquid This post is outdated

To add to Liquid's bag of tricks.

In JavaScript, we use the split() method to split a string into an array of strings on some delimiter character or string. In Liquid you can almost do the same, except you are not splitting a string into an array of strings but splitting it into a series of variables that store the resulting strings. Say you have a string of text, myText, and a delimiter character or substring, delimiter, and you wish to perform a Liquid full split.
{% assign myText = 'Pink - Small' %}
{% assign delimiter = ' - ' %}
{% capture myText %}{{ myText | replace: delimiter, ' ' }}{% endcapture %}
{% capture myFirstWord %}{{ myText | truncatewords: 1 | remove: '...' }}{% endcapture %}
{% capture mySecondWord %}{{ myText | replace: myFirstWord, '' }}{% endcapture %}

{{ myFirstWord }}

{% if mySecondWord == '' %}

No second word.

{% else %}

{{ mySecondWord }}

{% endif %}
This will output: Pink Small
Caroline from http://11heavens.com ∴ mllegeorgesand AT gmail DOT com
i
Replies
Posts:
5829
Last edited September 13, 2008

If you have to split something into 3 words, here is the code:

{% assign myText = 'Pink - Small - Hairy' %}
{% assign delimiter = ' - ' %}
{% capture myText %}{{ myText | replace: delimiter, ' ' }}{% endcapture %}
{% capture myFirstWord %}{{ myText | truncatewords: 1 | remove: '...' }}{% endcapture %}
{% capture myRest %}{{ myText | replace: myFirstWord, '' }}{% endcapture %}
{% capture mySecondWord %}{{ myRest | truncatewords: 1 | remove: '...' }}{% endcapture %}
{% capture myThirdWord %}{{ myRest | replace: mySecondWord, '' }}{% endcapture %}
<p>{{ myFirstWord }}</p>
{% if mySecondWord == '' %}
<p>No second word.</p>
{% else %}
<p>{{ mySecondWord }}</p>
{% endif %}
{% if myThirdWord == '' %}
<p>No third word.</p>
{% else %}
<p>{{ myThirdWord }}</p>
{% endif %}

This will output:

Pink

Small

Hairy

Caroline from http://11heavens.com ∴ mllegeorgesand AT gmail DOT com
Posts:
5829
September 13, 2008

So what is pink, small and hairy?

Probably a testicle.

Caroline from http://11heavens.com ∴ mllegeorgesand AT gmail DOT com
Posts:
5829
September 13, 2008

Although strictly-speaking… nah, ‘nough said.

Caroline from http://11heavens.com ∴ mllegeorgesand AT gmail DOT com
Jamie Chief Officer of Funness shopify.com/plus
Posts:
5861
September 28, 2008

This will output:Pink-Small-Hairy

:-O

Nice post :)

http://shopifyplus.com ::: http://twitter.com/bacchus
Posts:
6
January 09, 2009

Thanks Caroline, exactly what I was looking for. And I don’t even have to change anything since it’s for my testicle product.

Posts:
5829
January 09, 2009

@Batman: !!!

Intriguing, to say the least.

Caroline from http://11heavens.com ∴ mllegeorgesand AT gmail DOT com

Log in or sign up for an account to reply.

This thread has been closed! You will not be able to reply.