Module: Bridgetown::Filters::GroupingFilters

Included in:
Bridgetown::Filters
Defined in:
bridgetown-core/lib/bridgetown-core/filters/grouping_filters.rb

Instance Method Summary collapse

Instance Method Details

#group_by(input, property) ⇒ Array<Hash>

Group an array of items by a property, returning an array of hashes

Examples:

{"name"  => "larry"
 "items" => [...] } # all the items where `property` == "larry"

Parameters:

  • input (Enumerable)
  • property (String)

Returns:

  • (Array<Hash>)


15
16
17
18
19
20
21
22
# File 'bridgetown-core/lib/bridgetown-core/filters/grouping_filters.rb', line 15

def group_by(input, property)
  if groupable?(input)
    groups = input.group_by { |item| item_property(item, property).to_s }
    grouped_array(groups)
  else
    input
  end
end

#group_by_exp(input, variable, expression) ⇒ Array<Hash>

Group an array of items by an expression

Parameters:

  • input (Enumerable)
  • variable (String)

    variable to assign each item to in the expression

  • expression (String)

    Liquid comparison expression

Returns:

  • (Array<Hash>)


30
31
32
33
34
35
36
37
38
39
40
41
# File 'bridgetown-core/lib/bridgetown-core/filters/grouping_filters.rb', line 30

def group_by_exp(input, variable, expression)
  return input unless groupable?(input)

  parsed_expr = parse_expression(expression)
  @context.stack do
    groups = input.group_by do |item|
      @context[variable] = item
      parsed_expr.render(@context)
    end
    grouped_array(groups)
  end
end