Class: Each

Inherits:
BaseScopeFn show all
Defined in:
lib/emerald/nodes/each.rb

Overview

Function to map over elements in the context

Instance Method Summary collapse

Instance Method Details

#to_html(body, context) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/emerald/nodes/each.rb', line 9

def to_html(body, context)
  vars = collection.content(context)
  key_name = indexed.text_value.length.positive? ? indexed.key_name : nil

  # TODO: clean up somehow
  if vars.is_a? Hash
    vars
      .map do |var, key|
        new_ctx = context.clone
        new_ctx[val_name.text_value] = var
        new_ctx[key_name.text_value] = key if key_name

        body.to_html(new_ctx)
      end
      .join("\n")
  elsif vars.is_a? Array
    vars
      .map.with_index do |var, idx|
        new_ctx = context.clone
        new_ctx[val_name.text_value] = var
        new_ctx[key_name.text_value] = idx if key_name

        body.to_html(new_ctx)
      end
      .join("\n")
  elsif vars.nil?
    ''
  else
    raise 'bad variable type :('
  end
end