Seeing an error in output (Ruby language)

47 views Asked by At

This a code of product recommendations section which shows related products on cart and product details page

{% assign itemsPerColumn = columns | times:1 %}
{% assign perCol = count_product | divided_by: itemsPerColumn | ceil %}
{% assign leftOver = count_product | modulo: itemsPerColumn %}
{% assign numCols = perCol | plus: (leftOver > 0) | plus: (count_product == 1) %}
{% for row in (1..rows) %}
  <div class="row">
    {% for column in (1..columns) %}
      {% assign index = (forloop.index0 | times: rows) | plus: row | minus: 1 %}
      {% if index < count_product %}
        {% assign product = products[index] %}
        {% include 'product-card', max_height: max_height, product: product, show_vendor: show_vendor %}
      {% endif %}
    {% endfor %}
  </div>
{% endfor %}

i am seeing this error and cant find the solution:

Liquid syntax error (snippets/gp-product-related line 4): Expected dotdot but found comparison in "{{perCol | plus: (leftOver > 0) | plus: (count_product == 1) }}

I tried using module and removing parenthesis

1

There are 1 answers

0
Tom Lord On

The error is because parentheses are not valid syntax in Liquid.

But to be honest, most of your problem is the poorly named variables (and redundant code). Let's look line-by-line, and I'll point out all the weird things I see:


{% assign itemsPerColumn = columns | times:1 %}

What's going on here? Couldn't you just pass itemsPerColumn to the template, instead of a poorly-named columns variable?

And what's the point of times: 1? That's redundant code, delete it.


{% assign perCol = count_product | divided_by: itemsPerColumn | ceil %}

Another poorly named variable. This looks like you should be assigning numberOfColumns here.

Additionally, you're mixing camelCase with snake_case. Usually in ruby it's conventional to use snake_case for all variables, but both styles are valid... However, it's best to be consistent in which style you're using!


{% assign leftOver = count_product | modulo: itemsPerColumn %}

I'd call this leftOverItemsCount, not a vaguely-named leftOver. (Although again, we're mixing camelCase with snake_case...)


{% assign numCols = perCol | plus: (leftOver > 0) | plus: (count_product == 1) %}

The fatal error: Parentheses are not valid syntax in Liquid!

This code is actually not needed at all (as I'll show below), but you could write this logic in some way like:

{% assign numCols = perCol %}
{% if leftOver > 0 %}
  {% increment numCols %}
{% endif %}
{% if count_product == 1 %}
  {% increment numCols %}
{% endif %}

Now, back to my main answer. If we rename all of your variables to what they really represent, the logic becomes quite simple actually:

{% assign number_of_columns = count_product | divided_by: items_per_column | ceil %}
{% assign left_over_items_count = count_product | modulo: number_of_columns %}