Solved

Help with code: Split text after number of Characters

  • 16 February 2024
  • 4 replies
  • 66 views

Userlevel 1
Badge +3

Hi there :)

 

Can someone help me out with a quick question?

 

I’m currently using this code to split produt description text after full stop:  {{ catalog_item.description|split:'.'|lookup:'0' }} .

 

However, I’m looking to define a certain numer of characters instead as the split + ending the sentence after a whole word. So for instanse I want this: “The products is great for baking” not this  “The products is great for baking wit”

 

Best,

Mathilde

icon

Best answer by saulblum 26 February 2024, 15:05

View original

4 replies

Userlevel 4
Badge +7

Hi! A bit ugly, but this works:

{% with str="The product is great for baking chocolate chip cookies" %}

    {% with str2=str|slice:":35" %}

        {% with str_split=str2|split:" " %}

            {% with str_split_length=str_split|length|add:-1 %}

                {% with str_split_slice="0:"|concat:str_split_length %}

                    {{ str_split|slice:str_split_slice|join:" " }}

                {% endwith %}

            {% endwith %}

        {% endwith %}

    {% endwith %}

{% endwith %}

It takes the first 35 characters of the string (which I assume would come from the catalog item vs. being hard-coded), splits on spaces, and takes all but the last “word”, assuming the last one might be a partial word.

It’s not perfect, since if the last word is complete, it’d still remove it, but at least you don’t get partial words.

 

Userlevel 1
Badge +3

Hi!

 

Thanks for your answer :)

 

How would you include {{ catalog_item.description }} in your code as to avoid “{{ catalog_item.description }}“ being seen as the text itself, instad of the data it is supposed to pull?

Userlevel 4
Badge +7

Hi, this should work:

{% with str=catalog_item.description %}

Just make sure the whole thing is wrapped in a {% catalog %} block, per https://help.klaviyo.com/hc/en-us/articles/360004785571

 

 

Userlevel 1
Badge +3

I works thank you :)

Reply