我有一系列帖子,每个帖子都有一个类别。我想从这些类别的子集中显示3个帖子(我们会说a,b,c)。用核心液体有没有办法做到这一点?除非我没有想到我不认为有的东西。
帖子示例:
[
{title: post 1, category: {id: a}},
{title: post 2, category: {id: b}},
{title: post 3, category: {id: c}},
{title: post 4, category: {id: d}},
{title: post 5, category: {id: b}}
]
我需要像这样的伪代码:
{% for post in posts where category.id == a|b|c limit: 3 %}
或
{% for post in posts %}
{% if post.category.id == a|b|c limit: 3 %}
答案 0 :(得分:1)
这是一种方式:
{% assign counter = 0 %}
{% for post in posts %}
{% if counter < max and categories contains post.category.id %}
{% assign counter = counter | plus:1 %}
counter={{counter}}, post= {{post.title}}
{% endif %}
{% endfor %}
运行以下Ruby脚本:
#!/usr/bin/env ruby
require 'liquid.rb'
template = <<BLOCK
{% assign counter = 0 %}
{% for post in posts %}
{% if counter < max and categories contains post.category.id %}
{% assign counter = counter | plus:1 %}
counter={{counter}}, post= {{post.title}}
{% endif %}
{% endfor %}
BLOCK
posts = [
{ "title" => "post 1", "category" => { "id" => "a" } },
{ "title" => "post 2", "category" => { "id" => "e" } },
{ "title" => "post 3", "category" => { "id" => "c" } },
{ "title" => "post 4", "category" => { "id" => "d" } },
{ "title" => "post 5", "category" => { "id" => "f" } },
{ "title" => "post 6", "category" => { "id" => "b" } },
{ "title" => "post 7", "category" => { "id" => "e" } },
{ "title" => "post 8", "category" => { "id" => "b" } }
]
print Liquid::Template.parse(template).render({
'posts' => posts,
'max' => 3,
'categories' => ['a', 'b', 'c']
})
产生以下输出:
counter=1, post= post 1
counter=2, post= post 3
counter=3, post= post 6
(虽然剥离了一些换行符)
答案 1 :(得分:0)
您可以使用 Where Expression
{% assign posts = site.post
| where_exp:"p", "p.category.id = 'a' or p.category.id = 'b' or p.category.id = 'c'"
| limit: 3 %}
{% for post in posts %}
--> your code