[英]Jekyll / Liquid: Passing an Array into an Include and Looping
我試圖循環一個作為變量傳入include的數組,然后檢查變量是否與某個YAML匹配 - 如果是,我想打印結果。 我可以使用下面的代碼手動執行此操作,但是我需要一個可以在給定更大數組的情況下工作的解決方案。
首先,我從頁面傳遞這些信息:
<!--- Pass these variables into include.html --->
{% assign var_array = "D" %}
{% assign data = "object" %}
{% include include.html %}
我想消除所有eslif並替換為將遍歷整個數組的東西。
<!--- include.html --->
{% assign data = site.data.sheet.[data].last.items %}
{% assign sorted = var_array | split:"," %}
{% for item in data %}
{% if item.foo == sorted[0] %}
<p>{{ item.foo }}</p>
{% elsif item.foo == sorted[1] %}
<p>{{ item.foo }}</p>
{% elsif item.foo == sorted[2] %}
<p>{{ item.foo }}</p>
{% elsif item.foo == sorted[3] %}
<p>{{ item.foo }}</p>
{% endif %}
{% endfor %}
這是YAML數據:
<!--- sheet.yaml --->
object:
- items:
- foo: 'A'
- bar: 'text'
- items:
- foo: 'B'
bar: 'text'
- items:
- foo: 'C'
bar: 'text'
- items:
- foo: 'D'
bar: 'text'
這是所需的輸出:
<!-- Desired Output --->
<p>D</p>
我認為你需要的是一個嵌套的for
循環。
這應該做的伎倆:
{% for item in data %}
{% for s in sorted %}
{% if item.foo == s %}
<p>{{ item.foo }}</p>
{% endif %}
{% endfor %}
{% endfor %}
如果循環的兩個數組很大,這將產生許多迭代。 但是在Jekyll環境中,這只會在您開發項目的特定部分時執行。
順便說一句:在你的代碼中,你沒有將任何變量傳遞給包含的文件。 查看Jekyll文檔,了解如何正確執行此操作: https : //jekyllrb.com/docs/includes/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.