Jekyll将变量放在逻辑表达式中

时间:2014-05-25 02:49:55

标签: jekyll liquid

我试图执行以下操作:

{% for post in site.categories.{{ post.designer }} %}

因此,当将上述代码放在一个帖子中时,它可以显示当前帖子类别中的帖子列表。

然而,我不认为它正在工作,因为它只是不断返回未定义。我的问题是,是否可以在Jekyll或Liquid中将变量放在逻辑表达式中?

由于

1 个答案:

答案 0 :(得分:1)

我认为“设计师”是你帖子的类别? 如果是,则无法通过post.designer获取。

您需要使用page.categories代替(根据Page variables)。

帖子可以包含多个类别,因此您不能将page.categories放在循环中,因为它是一个数组。

有两种可能的解决方案:

  1. 遍历帖子的所有类别,然后为每个类别执行循环:

    {% for cat in page.categories %}
      <h1>{{ cat }}</h1>
      <ul>
        {% for post in site.categories[cat] %}
          <li><a href="{{ post.url }}">{{ post.title }}</a></li>
        {% endfor %}
      </ul>
    {% endfor %}
    
  2. 如果您的帖子只有一个类别,则可以省略我的第一个示例中的外部循环,然后使用the first element of the page.categories array

    <ul>
      {% for post in site.categories[page.categories.first] %}
        <li><a href="{{ post.url }}">{{ post.title }}</a></li>
      {% endfor %}
    </ul>
    

    {% assign firstcat = page.categories | first %}
    
    <ul>
      {% for post in site.categories[firstcat] %}
        <li><a href="{{ post.url }}">{{ post.title }}</a></li>
      {% endfor %}
    </ul>
    
相关问题