Class: Liquid::For
Constant Summary collapse
- Syntax =
/(\w+)\s+in\s+(#{AllowedVariableCharacters}+)/
Instance Attribute Summary
Attributes inherited from Tag
Instance Method Summary collapse
-
#initialize(markup, tokens) ⇒ For
constructor
A new instance of For.
- #render(context) ⇒ Object
Methods inherited from Block
#block_delimiter, #block_name, #create_variable, #end_tag, #parse, #unknown_tag
Methods inherited from Tag
Constructor Details
#initialize(markup, tokens) ⇒ For
Returns a new instance of For.
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
# File 'lib/liquid/standardtags.rb', line 93 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
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
# File 'lib/liquid/standardtags.rb', line 109 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 |