Class: Liquid::Template

Inherits:
Object show all
Defined in:
lib/zwite/liquid/ext/template.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#child_templateObject

Returns the value of attribute child_template.



6
7
8
# File 'lib/zwite/liquid/ext/template.rb', line 6

def child_template
  @child_template
end

#parent_templateObject

Returns the value of attribute parent_template.



5
6
7
# File 'lib/zwite/liquid/ext/template.rb', line 5

def parent_template
  @parent_template
end

Instance Method Details

#find_blocks(root, stack = {}) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/zwite/liquid/ext/template.rb', line 56

def find_blocks(root, stack = {})
  if root.respond_to?(:nodelist) && !root.nodelist.nil?
    root.nodelist.inject(stack) do |m, node|
      if node.is_a?(Zwite::Liquid::Block)
        m[node.name] = node
      end
      find_blocks(node, m)
      m
    end
  end
  return stack
end

#merge_blocks(root) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/zwite/liquid/ext/template.rb', line 69

def merge_blocks(root)
  unless @child_template.nil?
    blocks = find_blocks(root)
    child_blocks = find_blocks(@child_template.root)
    
    blocks.each do |name, block|
      if child_block = child_blocks[name]
        block.nodelist = child_block.nodelist
      end
    end
    
    @child_template.merge_blocks(root)
  end
end

#parse(source) ⇒ Object



8
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/zwite/liquid/ext/template.rb', line 8

def parse(source)
  # parse root normally
  @root = Document.new(tokenize(source))
  
  # check if root has any nodes otherwise skip early
  unless @root.nodelist.nil?
    
    # check if we have an "extends" node
    extends = nil
    @root.nodelist.each do |node|
      if node.is_a?(::Zwite::Liquid::Extends)
        extends = node
        break
      end
    end
    
    unless extends.nil?
      @parent_template = Template.new
      @parent_template.child_template = self
      @parent_template.parse(Template.file_system.read_template_file(extends.template_name))
    end
    
  end
  
  # perform merge if we're the last template in the tree
  if @parent_template && @child_template.nil?
    
    # get root template
    template = self
    while !template.parent_template.nil?
      template = template.parent_template
    end
    
    # merge blocks starting from root down to bottom
    template.merge_blocks(template.root)
    
    # swap our root nodelist to the root templates nodelist
    @root = template.root
    
    # discard parent/child templates
    @parent_template = nil
    @child_template = nil
    
  end
 
  self
end