液体中的阵列操作shopify

问题描述 投票:0回答:1

我试图在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'条件运行良好,我得到这样的输出

“与Isaac Newton一起介绍数学”。

我的问题是elsif,因此当教师的大小大于1.我明白了

“用艾萨克·马克介绍艾萨克牛顿数学的数学简介”。

我真正想要的是

“Isaac Newton和Elon Musk的数学简介”

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

ruby-on-rails ruby shopify liquid
1个回答
1
投票

问题是你希望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 %}
© www.soinside.com 2019 - 2024. All rights reserved.