jekyll数组可以有空格吗?

时间:2014-10-29 21:00:13

标签: arrays jekyll liquid

在我的前面,我有类似下面的类别。

categories: ['hello world', 'code', 'lunch']

但是当我试图将它们分解时,它会用空格而不是逗号分隔它们。我正在使用以下代码。

{% capture categories %}
{% for category in site.categories | join: ' '%}
{{ category[0] }}
{% endfor %}
{% endcapture %}

{% assign sortedcategories = categories | split:' ' | sort %}

{% for category in sortedcategories %}
<h3>{{ category }}</h3>

<ul>
{% for post in site.categories[category] %}
  <li>{{ post.url }}</li>
{% endfor %}

</ul>

{% endfor %}

我尝试使用分号作为分隔符但是当我到达site.categories [category]时,该部分失败并且不会在列表上显示任何内容。有任何想法吗?或者我应该使用没有空格的类别?或者使用连字符?

2 个答案:

答案 0 :(得分:0)

您要做的是:

{% assign sortedcategories = page.categories | sort %}

{% for category in sortedcategories %}
<h3>{{ category }}</h3>

<ul>
{% for post in site.categories[category] %}
  <li>{{ post.url }}</li>
{% endfor %}

</ul>

{% endfor %}

在您的前面,categories: ['hello world', 'code', 'lunch']创建一个数组。 而你在前五行中的表现毫无用处。

我还认为加入和分裂正在做的事情存在误解:

加入

{{ page.categories | join: "::" }} =&gt;字符串"hello world::code::lunch"

分割

{{ "hello world::code::lunch" | split: "::" =&gt;数组['hello world', 'code', 'lunch']

注意:

  • 使用page.variable
  • 到达前部主变量
  • 您不能在循环中使用过滤器。例如:{% for category in site.categories | sort %}您必须先分配一个变量,然后循环它。

答案 1 :(得分:-1)

好的,我得到了答案。换行非常重要。我不知道我读过多少次但我仍然忘记/忽略它。这是我的最终代码。

{% capture categories %}
  {% for category in site.categories %}{{ category | first }}{% unless forloop.last %},{% endunless %}{% endfor %}
{% endcapture %}

{% assign sortedcategories = categories | split: ',' | sort %}

{% for category in sortedcategories %}
  <h3>{{ category }}</h3>
  <ul>
    {% for post in site.categories[category] %}
      <li>{{ post.title }}</li>
    {% endfor %}
  </ul>
{% endfor %}

所以前三行代码创建了类别并存储了逗号分隔的所有site.categories值。这是我搞砸了的地方 - 第2行应该都是一行而不是分手。否则检查site.categories [category]的for循环永远不会匹配。这就是为什么我得到类别列表但我从来没有得到属于每个类别的帖子。