Class: Liquid::For

Inherits:
Block show all
Defined in:
lib/liquid/tags/for.rb

Constant Summary collapse

Syntax =
/(\w+)\s+in\s+(#{VariableSignature}+)/

Instance Attribute Summary

Attributes inherited from Tag

#nodelist

Instance Method Summary collapse

Methods inherited from Block

#block_delimiter, #block_name, #create_variable, #end_tag, #parse, #unknown_tag

Methods inherited from Tag

#name, #parse

Constructor Details

#initialize(markup, tokens) ⇒ For

Returns a new instance of For.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/liquid/tags/for.rb', line 5

def initialize(markup, tokens)
  super

  if markup =~ Syntax
    @variable_name = $1
    @collection_name = $2
    @name = "#{$1}-#{$2}"
    @attributes = {}
    markup.scan(TagAttributes) do |key, value|
      @attributes[key] = value
    end        
  else
    raise SyntaxError.new("Syntax Error in 'for loop' - Valid syntax: for [item] in [collection]")
  end
end

Instance Method Details

#render(context) ⇒ Object



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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/liquid/tags/for.rb', line 21

def render(context)        
  context.registers[:for] ||= Hash.new(0)

  collection = context[@collection_name]

  return '' if collection.nil? or collection.empty?

  range = (0..collection.length)

  if @attributes['limit'] or @attributes['offset']
  
  
    offset = 0
    if @attributes['offset'] == 'continue'
      offset = context.registers[:for][@name] 
    else          
      offset = context[@attributes['offset']] || 0
    end
  
    limit  = context[@attributes['limit']]

    range_end = limit ? offset + limit : collection.length
  
    range = (offset..range_end-1)
  
    # Save the range end in the registers so that future calls to 
    # offset:continue have something to pick up
    context.registers[:for][@name] = range_end
  end
        
  result = []
  segment = collection[range]
  return '' if segment.nil?        

  context.stack do 
    length = segment.length
  
    segment.each_with_index do |item, index|
      context[@variable_name] = item
      context['forloop'] = {
        'name'    => @name,
        'length'  => length,
        'index'   => index + 1, 
        'index0'  => index, 
        'rindex'  => length - index,
        'rindex0' => length - index -1,
        'first'   => (index == 0),
        'last'    => (index == length - 1) }
    
      result << render_all(@nodelist, context)
    end
  end

  # Store position of last element we rendered. This allows us to do 

  result 
end