Using variables with Liquid truncate filter in Shopify

I’m building a custom Shopify theme and encountering a problem with the truncate filter. I need to calculate how many characters to truncate dynamically based on some arithmetic.

Essentially, I want to sum the character count from both my product title and product description. Then I will subtract that total from 200 to get a final value. This value should be utilized for truncating my text, ensuring that all my product boxes have the same size.

Here’s my attempt, but it seems to be ineffective:

{% assign cutoffValue %}
{{ item.name.size | plus: item.content.size | minus: 200 }}
{% endassign %}

<div>{{ item.content | strip_html | replace: '&nbsp;', ' ' | truncate: cutoffValue }}</div>

The variable calculation is functioning correctly (if my total is 203, I receive 3) but it appears the truncate filter does not accept my variable. Can anyone explain this issue?

This is a super common issue with Liquid variables. You’re using capture-style syntax instead of direct assignment, which makes Liquid treat it as a string rather than doing the math. Try this instead: {% assign cutoffValue = item.name.size | plus: item.content.size | minus: 200 %}. This way the arithmetic gets processed and stored as a number that truncate can actually use. Just watch out for edge cases where your calculation goes negative or hits zero - that’ll mess with truncation. You might want to set a minimum value to avoid weird behavior.

Your variable assignment syntax is mixing capture and assign methods, which makes Liquid treat it as a string instead of a number. Use {% assign cutoffValue = item.name.size | plus: item.content.size | minus: 200 %} without the capture syntax. I ran into this exact same thing building a product grid - super frustrating to debug. Also watch out for zero or negative results since they’ll mess up your truncation. I’d add a safeguard to keep a minimum truncation value.

you’re def right about the assignment. make sure you set it correctly like this: {% assign cutoffValue = item.name.size | plus: item.content.size | minus: 200 %}. also, don’t let it go negative, or else the truncate will be a mess!