【问题标题】:can jekyll arrays have spaces?jekyll 数组可以有空格吗?
【发布时间】:2014-10-29 21:00:12
【问题描述】:

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

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] ​​时,该部分失败并且不会在列表中显示任何内容。有任何想法吗?或者我应该使用没有空格的类别?还是使用连字符?

【问题讨论】:

    标签: arrays jekyll liquid


    【解决方案1】:

    你想要做的是:

    {% 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'] 创建了一个数组。 而你在前五行中所做的一切都是无用的。

    我还认为对 join 和 split 的操作存在误解:

    加入

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

    拆分

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

    注意事项:

    • 通过page.variable 到达前端变量
    • 您不能在循环中使用过滤器。例如:{% for category in site.categories | sort %} 你必须先赋值给一个变量,然后循环遍历它。

    【讨论】:

    • 好吧,我要做的是创建一个 category.html 页面,其中列出了我使用过的所有类别。在每个类别中,我想列出具有该类别的帖子。这就是我使用 site.categories 而不是 page.categories 的原因。
    • 在您的问题中,您谈论的是正面问题。对我来说,这意味着您的数组已在您的页面/帖子中声明。
    【解决方案2】:

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

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

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

    【讨论】:

    • 你的前三行是site.categories | join:",",然后是split | sort。没用的。 site.categories | sort 就足够了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多