有条件地限制for循环的结果
Conditionally limit results of for loop
我想在 jekyll 博客中显示最后 10 post 秒,假设它们的 show
属性是 true
。
例如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 个中有一个 post 的 show
属性为 false
,则页面上只会出现 9 post。
Jinja2 支持 for-if
语法,如下所示:http://jinja.pocoo.org/docs/dev/templates/#for。这将解决我的问题,但遗憾的是不支持 liquid。
如何使用 liquid 以 post 属性为条件并确保始终显示 10 posts?
尝试将 assign
用于 post 的计数器变量 ,并将 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.
或者, 我觉得你只想设置是否应该发布 post,在这种情况下,您 可以使用内置的 published
变量。只需在前面做 published : true
或 published : false
即可。阅读有关预定义变量的更多信息 here.
您必须首先创建一个数组,其中包含将 show
变量设置为 true
的帖子。
{% assign publishedPosts = site.posts | where: 'show', 'true' %}
然后你可以制作一个
{% for p in publishedPosts limit:10 %}
只是在@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 %}
我需要这个,因为我在标签中使用包含。由于某种原因,增量无法正常工作。
我想在 jekyll 博客中显示最后 10 post 秒,假设它们的 show
属性是 true
。
例如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 个中有一个 post 的 show
属性为 false
,则页面上只会出现 9 post。
Jinja2 支持 for-if
语法,如下所示:http://jinja.pocoo.org/docs/dev/templates/#for。这将解决我的问题,但遗憾的是不支持 liquid。
如何使用 liquid 以 post 属性为条件并确保始终显示 10 posts?
尝试将 assign
用于 post 的计数器变量 ,并将 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.
或者, 我觉得你只想设置是否应该发布 post,在这种情况下,您 可以使用内置的 published
变量。只需在前面做 published : true
或 published : false
即可。阅读有关预定义变量的更多信息 here.
您必须首先创建一个数组,其中包含将 show
变量设置为 true
的帖子。
{% assign publishedPosts = site.posts | where: 'show', 'true' %}
然后你可以制作一个
{% for p in publishedPosts limit:10 %}
只是在@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 %}
我需要这个,因为我在标签中使用包含。由于某种原因,增量无法正常工作。