Class: Twig::Node::Module

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

Instance Attribute Summary

Attributes inherited from Base

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

Instance Method Summary collapse

Methods inherited from Base

#empty?, #length, #template_name, #to_s

Constructor Details

#initialize(body, parent, blocks, macros, traits, embedded_templates, source) ⇒ Module

Returns a new instance of Module.

Parameters:



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/twig/node/module.rb', line 7

def initialize(body, parent, blocks, macros, traits, embedded_templates, source)
  nodes = {
    body:,
    blocks:,
    macros:,
    traits:,
  }
  nodes[:parent] = parent if parent

  super(
    nodes,
    {
      index: nil,
      embedded_templates:,
    },
    1
  )

  self.source_context = source
end

Instance Method Details

#compile(compiler) ⇒ Object



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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/twig/node/module.rb', line 32

def compile(compiler)
  class_name = compiler.environment.template_class(source_context.name, attributes[:index])
  class_begin = <<~CLASS
    class Twig::#{class_name} < ::Twig::Template
  CLASS

  class_end = <<~CLASS
    end
  CLASS

  compiler.
    raw(class_begin).
    indent

  compile_constructor(compiler)
  compile_get_parent(compiler)

  compiler.
    write("private def call(context = {}, blocks = {})\n").
    indent.
    write("unless context.is_a?(::Twig::Runtime::Context)\n").
    indent.
    write("context = ::Twig::Runtime::Context.new(context)\n").
    outdent.
    write("end\n").
    write("macros = @macros.dup\n")

  compiler.
    subcompile(nodes[:body])

  if nodes.key?(:parent)
    parent = nodes[:parent]
    compiler.add_debug_info(parent)

    if parent.is_a?(Expression::Constant)
      compiler.
        write('@parent = load(').
        subcompile(parent).
        raw(', ').
        repr(parent.lineno).
        raw(")\n").
        write('@parent')
    else
      compiler.write('get_parent(context)')
    end

    compiler.
      raw(".unwrap.render_with_blocks(context, self.blocks.merge(blocks));\n")
  end

  compiler.
    write("context.output_buffer\n").
    outdent.
    write("end\n\n")

  # Blocks
  compiler.
    subcompile(nodes[:blocks])

  # Macros
  compiler.
    subcompile(nodes[:macros])

  compile_get_template_name(compiler)
  compile_traitable(compiler)
  compile_debug_info(compiler)
  compile_get_source_context(compiler)

  compiler.
    outdent.
    raw(class_end)

  attributes[:embedded_templates].nodes.each_value do |template|
    compiler.subcompile(template)
  end
end

#index=(index) ⇒ Object



28
29
30
# File 'lib/twig/node/module.rb', line 28

def index=(index)
  attributes[:index] = index
end