2014-03-29 46 views
2

我有一個帖子數組,每個帖子都有一個類別。我想從這些類別的子集中顯示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 %} 

回答

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 

(剝離一些換行符雖然)