我有一个包含不同项目的数据文件。每个项目都有嵌套的任务。我正在尝试循环嵌套任务并按任务类型呈现每个任务。
YML数据
- name: Outside
description: Description
tasks:
- type: Food
name: Eat it outside
status: working
- type: Drinks
name: Drink it outside
status: working
- name: Inside
description: Description
tasks:
- type: Food
name: Eat it inside
status: pending
- type: Drinks
name: Drink it inside
status: working
液体
{% for item in site.data.info %}
{% assign grouped-tasks-by-type = item.tasks | group_by: "type" %}
{% for task in grouped-tasks-by-type %}
<h2 class="task-type">{{ task.type }}</h2>
<ul>
{% for task in item.tasks %}
{% if task.status == 'working' %}
<li>{{ item.name }}: {{ task.name }}</li>
{% endif %}
{% endfor %}
</ul>
{% endfor %}
{% endfor %}
预期结果 (HTML)
<h2 class="task-type">Food</h2>
<ul>
<li>Outside: Eat it outside<li>
</ul>
<h2 class="task-type">Drinks</h2>
<ul>
<li>Outside: Drink it outside<li>
<li>Inside: Drink it inside<li>
</ul>
但是,我得到一个完全空白的结果。这可能与
group_by
有关吗? ?
最佳答案
我希望我下面的算法可以很好地为您服务。我能够通过算法实现您期望的最终结果。我无法使用 group_by
在我的解决方案中。示例代码包含 Liquid 注释块来解释我的思考过程。
测试
我用了 minima git repo , 使用命令 jekyll s
.我将您的 YML 数据放在一个文件中,路径为 _data/info.yml
在我本地克隆的 minima git repo 中。我用过 post.html
作为代码沙箱。
您可以通过执行 {{ all_food_types | json }}
将 Liquid 变量打印到 DOM。在代码中。
解决方案
{%- comment -%}
End Goal: Find all the food types for <h2>.
1. Use map: "tasks" to gather all the tasks into a single array.
This will cause the loss of Outside/Inside information for each task
2. Use map: "type" to create a list of food types ("Food", "Drinks")
3. Use uniq to remove duplicate food types from the array
{%- endcomment -%}
{% assign all_food_types = site.data.info | map: "tasks" | map: "type" | uniq %}
{%- comment -%}
End Goal: Loop through all the data looking
for a specific food type (Food, Drinks)
and group them together
{%- endcomment -%}
{% for food_type in all_food_types %}
<h2 class="task-type">{{ food_type }}</h2>
<ul>
{% for item in site.data.info %}
{% for task in item.tasks %}
{% if task.status == 'working' and task.type == food_type %}
<li>{{ item.name }}: {{ task.name }}</li>
{% endif %}
{% endfor %}
{% endfor %}
</ul>
{% endfor %}
顺便说一句,无论出于何种原因,我的液体最终使用了大量数组和 for 循环。
关于jekyll - 在 Jekyll 的嵌套数据树中循环唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61475615/