Class: H2o::Tags::For
Constant Summary collapse
- Syntax =
/ (?:(#{H2o::IDENTIFIER_RE}),\s?)? (#{H2o::IDENTIFIER_RE})\s+in\s+(#{H2o::NAME_RE})\s* (reversed)? /x
Instance Method Summary collapse
-
#initialize(parser, argstring) ⇒ For
constructor
A new instance of For.
- #render(context, stream) ⇒ Object
Constructor Details
#initialize(parser, argstring) ⇒ For
Returns a new instance of For.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/h2o/tags/for.rb', line 10 def initialize(parser, argstring) @key = false @else = false @body = parser.parse(:else, :endfor) @else = parser.parse(:endfor) if parser.token && parser.token.include?('else') if matches = Syntax.match(argstring) @key = $1.to_sym unless $1.nil? @item = $2.to_sym @iteratable = $3.to_sym @reverse = !$4.nil? else raise SyntaxError, "Invalid for loop syntax " end end |
Instance Method Details
#render(context, stream) ⇒ Object
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 |
# File 'lib/h2o/tags/for.rb', line 26 def render(context, stream) iteratable = context.resolve(@iteratable) iteratable.reverse! if @reverse length = 0 if iteratable.respond_to?(:each) length = iteratable.size || iteratable.length end if length > 0 parent = context[:loop] index = 0 # Main iteration context.stack do iteratable.each do |item| if item.is_a?(Array) key, value = item else key = index value = item end is_even = index % 2 != 0 rev_count = length - index context[@item] = value context[@key] = key context[:loop] = { :parent => parent, :first => index == 0, :last => rev_count == 1, :counter => index + 1, :counter0 => index, :revcounter => rev_count, :revcounter0 => rev_count - 1, :even => is_even, :odd => !is_even } @body.render(context, stream) index += 1 end end else # Else statement @else.render(context, stream) if @else end nil end |