【问题标题】:Conditionally limit results of for loop有条件地限制for循环的结果
【发布时间】:2015-09-25 17:06:32
【问题描述】:

假设他们的show 属性是true,我想在一个jekyll 博客中显示最后10 个帖子。

例如YAML 前面的内容可能是这样的

---
title: "SO question"
categories: question
show: false
---

在我的index.html 文件中,我目前有以下内容

{% for post in site.posts limit:10 %} 
  {% if post.show %}
    <!-- display post -->
  {% endif %}
{% endfor %}

但如果最后 10 个帖子中的一个帖子的 show 属性为 false,则页面上只会显示 9 个帖子。

Jinja2 支持for-if 语法,如下所示:http://jinja.pocoo.org/docs/dev/templates/#for。这将解决我的问题,但不幸的是不支持液体。

使用液体,我如何以帖子属性为条件并确保始终显示 10 个帖子?

【问题讨论】:

    标签: jekyll liquid


    【解决方案1】:

    您必须首先创建一个数组,其中包含将show 变量设置为true 的帖子。

    {% assign publishedPosts = site.posts | where: 'show', 'true' %}
    

    然后你可以做一个

    {% for p in publishedPosts limit:10 %}
    

    【讨论】:

    • 不知道你可以用液体做到这一点,太好了! +1
    【解决方案2】:

    只是指出@matrixanonaly 的答案,如果不能使用“where”过滤器,它可以在一个小的 tweek 中很好地工作。我还不能发表评论,但我想我会修复它,让它像它帮助我一样工作。

     {% assign count = 0 %}
       {% for post in site.posts limit:10 %} 
         {% if post.show %}
             {% if count < 10 %} 
             <!-- display post -->
             {% assign count = count | plus: 1 %}
             {% endif %}
       {% endif %}
    {% endfor %}
    

    我需要这个,因为我在标签中使用了 contains。由于某种原因,增量不起作用。

    【讨论】:

      【解决方案3】:

      尝试将assign 用于将show 值设置为true 的帖子的计数器变量。这是一些简单的方法之一。

      {% assign count = 0 %}
         {% for post in site.posts limit:10 %} 
           {% if post.show %}
               {% if count < 10 %} 
               <!-- display post -->
               {% increment count %}
               {% endif %}
         {% endif %}
      {% endfor %}
      

      应该可以工作,但是我现在没有安装 Jekyll 来检查,或者如果增量不起作用,请使用 {% assign count = count + 1 %}

      Shopify Liquid syntax manual is helpful

      或者, 我有一种感觉,您只想设置是否应该发布帖子,在这种情况下,您可以使用内置的在 published 变量中。只需在frontmatter 中执行published : truepublished : false。阅读更多关于预定义变量的信息here

      【讨论】:

        猜你喜欢
        • 2016-04-14
        • 2020-12-15
        • 2018-06-04
        • 1970-01-01
        • 2017-12-08
        • 2018-09-06
        • 2022-07-21
        • 1970-01-01
        • 2018-06-26
        相关资源
        最近更新 更多