Ad

Array Manipulation In Liquid Shopify

- 1 answer

I am trying to work out a conditional iteration in Liquid. This is what i have

 {% capture title_tag %}
    {% for teacher in course.teachers %}
      {% if course.teachers.size == 1 %}
        {{course.title}} with {{ teacher.name | escape }}
      {% elsif course.teachers.size > 1 %}
        {{ course.title }} with {{ teacher.name }} 
       {% endif %}
    {% endfor %}
 {% endcapture %}

As expected, the first 'if' condition works well and i get an output like this

"Intro to Maths with Isaac Newton".

My problem is with the elsif, thus when the teacher size is greater than 1. I get this

"Intro to Maths with Isaac Newton Intro to Maths with Elon Musk".

What I actually want is

"Intro to Maths with Isaac Newton and Elon Musk"

I would appreciate any help. Thanks

Ad

Answer

The issue is you want the course.title to be printed not inside a loop.

{% capture title_tag %}
  {{ course.title }} with  ⇐ !!!! HERE
  {% for teacher in course.teachers %}
    {% if course.teachers.size == 1 %}
      {{ teacher.name | escape }}
    {% elsif course.teachers.size > 1 %}
      {{ teacher.name }} 
    {% endif %}
  {% endfor %}
{% endcapture %}

joining the names with and is more tricky and requires additional coding. Maybe you should just use String#join:

{% capture title_tag %}
  {{ course.title }} with
  {{ course.teachers.map { |t| t.name }.join(', ') }}
{% endcapture %}
Ad
source: stackoverflow.com
Ad