您可以通过索引来识别一列:
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>
编辑:
您还可以使用来自页面逻辑的选择数组,例如 {% assign displayCol = "1,2,4" | split: "," %}(从字符串创建数组,这是在页面代码中创建数组的唯一方法),引用为 displayCol 而不是 page.displayCol。
问题在于它创建了一个字符串数组:{% assign displayCol = "1,2,4" | split: "," %} => ["1", "2", "4"]。并且不可能在字符串数组中测试 forloop.index(integer) 的存在。
解决方案是将 forloop.index 转换为带有 {% assign indexToStr = forloop.index | append:"" %} 的字符串
结果代码将是:
{% 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>