For loop 对于循环和Jekyll:在循环中选择特定索引?

For loop 对于循环和Jekyll:在循环中选择特定索引?,for-loop,jekyll,For Loop,Jekyll,假设您有一个数据库: 品牌|型号|序列号|位置| IP地址|服务日期|等 为了创建列标题,我标识循环中的第一个,然后使用字段[0]为集合中的每一列运行另一个for循环。然后,我从左到右对数据和字段[1]数据运行另一个for循环 这很好地构建了表。如何遍历字段[1]进行循环并有选择地选择每一列?假设在一个页面中,我想显示品牌|型号|序列号,但在另一个页面中,我只想包括品牌|型号| IP地址 到目前为止,我唯一能做到这一点的方法是在循环的字段中放置一个forloop.index条件,以查找{%if-

假设您有一个数据库:

品牌|型号|序列号|位置| IP地址|服务日期|等

为了创建列标题,我标识循环中的第一个,然后使用字段[0]为集合中的每一列运行另一个for循环。然后,我从左到右对数据和字段[1]数据运行另一个for循环

这很好地构建了表。如何遍历字段[1]进行循环并有选择地选择每一列?假设在一个页面中,我想显示品牌|型号|序列号,但在另一个页面中,我只想包括品牌|型号| IP地址

到目前为止,我唯一能做到这一点的方法是在循环的字段中放置一个forloop.index条件,以查找{%if-forloop.index==1和forloop.index==3%}作为示例,等等。这似乎效率不高

<table>

{% for item in site.data.equipment %}

  {% if forloop.first == true %}

  <tr>
   {% for field in item %}
    <th>{{ field[0] }}</th>
   {% endfor %}
  </tr>

  {% endif %}

  {% for item in site.data.equipment %}

  <tr>
    <td>{{ field[1] }}</td>
  </tr>

  {% endfor %}

{% endfor %}
</table>

您可以通过索引标识列:

Brand | Model | Serial No | Location | IP Address
1       2       3           4          5
然后可以基于简单数组选择打印列。在本例中,它存储在页面首页,但也可以放在前面_config.yml

---
# page front matter
# ....
displayCol: [1,2,4]
---
{% assign equipment = site.data.equipment %}

<table>
{% for item in equipment %}
  {% if forloop.first == true %}
    <tr>
    {% for field in item %}
      {% if page.displayCol contains forloop.index %}
      <th>{{ field[0] }}</th>
      {% endif %}
    {% endfor %}
    </tr>
  {% endif %}

  <tr>
  {% for field in item %}
    {% if page.displayCol contains forloop.index %}
    <td>{{ field[1] }}</td>
    {% endif %}
  {% endfor %}
  </tr>

{% endfor %}
</table>

在不使用front matter的情况下,是否可以在包含[1,2,4]的逻辑内部定义一个数组,然后使用该变量,或者它仅限于front matter?是的,这将起作用,因为我可以根据页面名称的直接结果分配displayCol。因此,如果pages文件夹中的页面名为equipment_list_sound.md,并且它包含逻辑页面_includes/equipment_list.html,那么在逻辑中,我可以从{page.name}中删除设备_list_uuu,使其只剩下声音,然后运行一个条件,即如果X=sound,那么displayCol=Y,否则,如果X=lights,则displayCol=Z。对于不属于注释一部分的元素,注释不是询问其他问题的地方。记下答案,如果需要,再问一个新问题。这不是问题。好的,我明白你的意思。
{% assign equipment = site.data.equipment %}
{% comment %}Here is the setup for displayed columns{% endcomment %}
{% assign displayCol = "1,2,4" | split: "," %}

<table>
{% for item in equipment %}
  {% if forloop.first == true %}
    <tr>
    {% for field in item %}
      {% assign indexToStr = forloop.index | append: "" %}
      {% if displayCol contains indexToStr %}
      <th>{{ field[0] }}</th>
      {% endif %}
    {% endfor %}
    </tr>
  {% endif %}

  <tr>
  {% for field in item %}
    {% assign indexToStr = forloop.index | append: "" %}
    {% if displayCol contains indexToStr %}
    <td>{{ field[1] }}</td>
    {% endif %}
  {% endfor %}
  </tr>

{% endfor %}
</table>