Liquid shopify 中的数组操作

Array Manipulation in Liquid shopify

我正在尝试在 Liquid 中进行条件迭代。这就是我的

 {% 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 %}

正如预期的那样,第一个 'if' 条件运行良好,我得到这样的输出

"Intro to Maths with Isaac Newton".

我的问题是 elsif,因此当教师人数大于 1 时。我得到这个

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

其实我想要的是

"Intro to Maths with Isaac Newton and Elon Musk"

如有任何帮助,我将不胜感激。谢谢

问题是您希望 course.title 打印 而不是在循环内

{% 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 %}

将名称与 and 连接起来比较棘手,需要额外的编码。也许你应该只使用 String#join:

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