我有一系列帖子,每个帖子都有一个类别。我想显示这些类别子集的 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 %}
最佳答案
这里有一个方法:
{% 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
(不过删除了一些换行符)
关于循环条件的液体数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22737424/