DNS
DNS

Reputation: 38199

Is there a way to split text on whitespace in Liquid?

I'm trying to split a Jekyll post's contents into words, and have tried the following:

{% for word in post.content | split:' ' %}
    {% do some stuff %}
{% endfor %}

Unfortunately this doesn't do anything; 'word' ends up as the whole post. I'm using this code on Github Pages, so unfortunately I can't write a plug-in to take care of this. Am I using the split filter incorrectly? Does Liquid support what I'm trying to do?

Upvotes: 3

Views: 4890

Answers (2)

Andrew
Andrew

Reputation: 358

It seems that you can split on whitespace by using split: .

So you can try something like:

{% capture words %}{{ post.content | split:  }}{% endcapture %}

or:

{% assign words = post.content | split:  %}

From what I've tested so far it seems that you should use the latter (assign tag), as the capture tag seems to do an implicit join on the array elements when assigning the value to the variable.

Using:

{% for post in site.posts limit:1 offset:6 %}
  {% assign words = post.content | split:  %}
  {% for word in words %}{{ word }} {% endfor %}
{% endfor %}

seems reproduce the post content in its entirety. The whitespace in the inner for loop matters.

Just as a note now, if you need to join some of the words back together with whitespace, the join tag seems to require quotes around the character, like so: join:' '.

Edit:

I ended up attempting to also do some splitting on whitespace, and while it worked in my development environment it didn't work on Github Pages. It looks like Pages is running version 2.2.2, whereas the split() filter was introduced in version 2.3.0. My development environment was running 2.4.1. Hopefully we can pester the fine folks at Github enough to get them to update their version of Liquid. :)

Upvotes: 10

Brad Johnson
Brad Johnson

Reputation: 31

Filters (such as split) can only be used on {{ outputs }} not on {% tags %}.

You might be able to accomplish the split by using the capture function as follows: {% capture 'foo' %} {{ post.content | split:' ' }} {% endcapture %}

Upvotes: 3

Related Questions