Class: Twig::Node::For

Inherits:
Base
  • Object
show all
Defined in:
lib/twig/node/for.rb

Instance Attribute Summary

Attributes inherited from Base

#attributes, #lineno, #nodes, #source_context, #tag

Instance Method Summary collapse

Methods inherited from Base

#template_name

Constructor Details

#initialize(key_target, value_target, seq, if_expr, body, else_expr, lineno) ⇒ For

Returns a new instance of For.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/twig/node/for.rb', line 6

def initialize(key_target, value_target, seq, if_expr, body, else_expr, lineno)
  loop = ForLoop.new(lineno)
  body = Nodes.new(AutoHash.new.add(body, loop))

  nodes = {
    key_target:,
    value_target:,
    seq:,
    body:,
  }

  unless else_expr.nil?
    nodes[:else_expr] = else_expr
  end

  super(nodes, { with_loop: true }, lineno)
end

Instance Method Details

#compile(compiler) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/twig/node/for.rb', line 24

def compile(compiler)
  compiler.
    write("context.push_stack\n").
    write('context[:_seq] = ::Twig::Extension::Core.ensure_hash(').
    subcompile(nodes[:seq]).
    raw(")\n")

  # @todo Missing some more loops stuff here

  if nodes.key?(:else_expr)
    compiler.write("context[:_iterated] = false\n")
  end

  compiler.
    write("context[:_seq].each do |k, v|\n").
    indent.
    write('').
    subcompile(nodes[:key_target]).
    raw(" = k\n").
    write('').
    subcompile(nodes[:value_target]).
    raw(" = v\n\n").
    subcompile(nodes[:body]).
    outdent.
    write("end\n")

  if nodes.key?(:else_expr)
    compiler.
      write("unless context[:_iterated]\n").
      indent.
      subcompile(nodes[:else_expr]).
      outdent.
      write("end\n")
  end

  compiler.
    write("context.pop_stack\n")
end