循环条件的液体数组?

标签 liquid

我有一系列帖子,每个帖子都有一个类别。我想显示这些类别子集的 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/

相关文章:

html 不是完全流动的

ruby - 如何修复 : Liquid Exception: Tag '{%' was not properly terminated with regexp:/\%\}/?

ruby-on-rails - 将 Liquid 模板过滤器绑定(bind)到上下文

Jekyll 显示子类别的帖子数

jekyll - 迭代 Markdown 标题以创建导航菜单

syntax - 液体警告 : Liquid syntax error: Expected end_of_string but found id in

javascript - 删除 id 会杀死页面上的所有 javascript

html - Jekyll 中输出多个段落标签

ruby-on-rails - 液体中的部分

html - Shopify/Liquid 找到 "-"并删除之前的内容