Class: Twig::Node::ForLoop

Inherits:
Base
  • Object
show all
Defined in:
lib/twig/node/for_loop.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(lineno) ⇒ ForLoop

Returns a new instance of ForLoop.



6
7
8
# File 'lib/twig/node/for_loop.rb', line 6

def initialize(lineno)
  super({}, { with_loop: false, if_expr: false, else_expr: false }, lineno)
end

Instance Method Details

#compile(compiler) ⇒ Object



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
# File 'lib/twig/node/for_loop.rb', line 10

def compile(compiler)
  if attributes.key?(:else_expr)
    compiler.write("context[:_iterated] = true\n")
  end

  # @todo if with loop
  compiler.
    write("context[:loop] = {\n").
    write("  index0: 0,\n").
    write("  index: 1,\n").
    write("  first: true,\n").
    write("}\n")

  if attributes.key?(:with_loop)
    compiler.
      write("context[:loop][:index0] += 1\n").
      write("context[:loop][:index] += 1\n").
      write("context[:loop][:first] = false\n").
      write("if context[:loop].key?(:revindex0) && context[:loop].key?(:revindex)\n").
      indent.
      write("context[:loop][:revindex0] -= 1\n").
      write("context[:loop][:revindex] -= 1\n").
      write("context[:loop][:last] = (context[:loop][:revindex0] == 0)\n").
      outdent.
      write("end\n")
  end
end