首页 > 解决方案 > Jekyll 嵌套包含与 for 循环

问题描述

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

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

{% 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" %}

标签: jekyllgithub-pages

解决方案


它可能是另一个更优雅(?)的解决方案开发插件,但可以快速修改您的代码,在_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" %}

推荐阅读