Class: Nm::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/nm/context.rb

Instance Method Summary collapse

Constructor Details

#initialize(context, source:, locals:) ⇒ Context

Returns a new instance of Context.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/nm/context.rb', line 8

def initialize(context, source:, locals:)
  @context = context
  @source = source

  # apply template behaviors to the meta-context
  metacontext = class << context; self; end
  metacontext.class_eval do
    include Nm::TemplateBehaviors

    locals.each do |key, value|
      define_method(key){ value }
    end
  end
  @context.__nm_context__ = self
end

Instance Method Details

#render(template_name, locals = {}) ⇒ Object Also known as: partial



24
25
26
27
28
29
30
31
# File 'lib/nm/context.rb', line 24

def render(template_name, locals = {})
  source_file_path = @source.file_path!(template_name)
  render_content(
    @source.data(source_file_path),
    locals: locals,
    file_path: source_file_path,
  )
end

#render_content(content, locals: {}, file_path: nil) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/nm/context.rb', line 35

def render_content(content, locals: {}, file_path: nil)
  @context.__nm_push_render__(locals.to_h)
  @context.instance_eval(
    "#{locals_code_for(locals)};#{content}",
    file_path,
    1,
  )
  @context.__nm_data__.tap{ |_data| @context.__nm_pop_render__ }
end