我有一个包含不同项目的数据文件。每个项目都有嵌套的任务。我正在尝试循环嵌套任务并按任务类型呈现每个任务。
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
Run Code Online (Sandbox Code Playgroud)
液体
{% 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 %}
Run Code Online (Sandbox Code Playgroud)
预期结果 (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>
Run Code Online (Sandbox Code Playgroud)
但是,我得到一个完全空白的结果。这可能与group_by吗?
我希望我下面的算法可以很好地为您服务。我能够通过算法实现您期望的最终结果。我无法group_by在我的解决方案中使用 。示例代码包含 Liquid 注释块来解释我的思考过程。
我使用了minima git repo和 command jekyll s。我将您的 YML 数据放在_data/info.yml我本地克隆的最小 git存储库中带有路径的文件中。我用作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 %}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,无论出于何种原因,我的液体最终使用了大量数组和 for 循环。
| 归档时间: |
|
| 查看次数: |
240 次 |
| 最近记录: |