Skip to main content
Problem Solver I
February 16, 2024
Solved

Help with code: Split text after number of Characters

  • February 16, 2024
  • 4 replies
  • 427 views

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

    This topic has been closed for replies.
    Best answer by saulblum

    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

     

     

    4 replies

    Klaviyo Employee
    February 16, 2024

    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.

     

    MathildeAuthor
    Problem Solver I
    February 17, 2024

    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?

    saulblumAnswer
    Klaviyo Employee
    February 26, 2024

    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

     

     

    MathildeAuthor
    Problem Solver I
    February 27, 2024

    I works thank you :)