Jekyll 嵌套包含 for 循环

Jekyll nested include with for loop

我想在包含的文件中使用 {% for %} 循环,以避免重复创建循环数组的逻辑(它是一个 assign 和多个 where_exp)。

但我想根据包含循环的位置使用不同的内容,所以有时我会这样做:

{% for i in a %}
<li>{{ i.name }}</li>
{% endfor %}

有时:

{% for i in a %}
<loc>{{ i.url }}</loc>
{% endfor %}

我怎样才能做到这一点?到目前为止,我必须将每个内部内容放在它们自己的模板中,所以我会有如下所示的文件,但我想避免额外的 template 文件,并将该内容保留在适当的 main 文件:

html_template.html:

<li>{{ i.name }}</li>

xml_template.xml:

<loc>{{ i.url }}</loc>

page_loop.html:

{% assign a = "logic I don't want to repeat" %}
{% for i in a %}
{% include {{ include.inner_template }} %}
{% endfor %}

html_main.html:

{% include page_loop.html inner_template="html_template.html" %}

xml_main.xml:

{% include page_loop.html inner_template="xml_template.xml" %}

这可能是另一个更 优雅 (?) 解决方案开发插件,但快速修改您的代码,在 _includes/page_loop.html:

{% assign a = "something" %}
{% for i in a %}
{%if include.type == "name"%}
<li>{{ i.name }}</li>
{%else if include.type == "url"%}
<loc>{{ i.url }}</loc>
{%endif %}
{% endfor %}

然后每次包含 page_loop.html 时传递一个附加参数,指定您想要的输出类型:

{% include page_loop.html type="name" %}

{% include page_loop.html type="url" %}