Class: Liquid::For
Overview
“For” iterates over an array or collection. Several useful variables are available to you within the loop.
Basic usage:
{% for item in collection %}
{{ forloop.index }}: {{ item.name }}
{% endfor %}
Advanced usage:
{% for item in collection %}
<div {% if forloop.first %}class="first"{% endif %}>
Item {{ forloop.index }}: {{ item.name }}
</div>
{% else %}
There is nothing in the collection.
{% endfor %}
You can also define a limit and offset much like SQL. Remember that offset starts at 0 for the first item.
{% for item in collection limit:5 offset:10 %}
{{ item.name }}
{% end %}
To reverse the for loop simply use {% for item in collection reversed %}
Available variables:
- forloop.name
-
‘item-collection’
- forloop.length
-
Length of the loop
- forloop.index
-
The current item’s position in the collection; forloop.index starts at 1. This is helpful for non-programmers who start believe the first item in an array is 1, not 0.
- forloop.index0
-
The current item’s position in the collection where the first item is 0
- forloop.rindex
-
Number of items remaining in the loop (length - index) where 1 is the last item.
- forloop.rindex0
-
Number of items remaining in the loop where 0 is the last item.
- forloop.first
-
Returns true if the item is the first item.
- forloop.last
-
Returns true if the item is the last item.
- forloop.parentloop
-
Provides access to the parent loop, if present.
Constant Summary collapse
- Syntax =
/\A(#{VariableSegment}+)\s+in\s+(#{QuotedFragment}+)\s*(reversed)?/o
Instance Attribute Summary
Attributes inherited from Tag
#line_number, #parse_context, #tag_name
Instance Method Summary collapse
-
#initialize(tag_name, markup, options) ⇒ For
constructor
A new instance of For.
- #nodelist ⇒ Object
- #parse(tokens) ⇒ Object
- #render(context) ⇒ Object
- #unknown_tag(tag, markup, tokens) ⇒ Object
Methods inherited from Block
#blank?, #block_delimiter, #block_name
Methods inherited from Tag
Methods included from ParserSwitching
Constructor Details
Instance Method Details
#nodelist ⇒ Object
62 63 64 |
# File 'lib/liquid/tags/for.rb', line 62 def nodelist @else_block ? [@for_block, @else_block] : [@for_block] end |
#parse(tokens) ⇒ Object
57 58 59 60 |
# File 'lib/liquid/tags/for.rb', line 57 def parse(tokens) return unless parse_body(@for_block, tokens) parse_body(@else_block, tokens) end |
#render(context) ⇒ Object
71 72 73 74 75 76 77 78 79 |
# File 'lib/liquid/tags/for.rb', line 71 def render(context) segment = collection_segment(context) if segment.empty? render_else(context) else render_segment(context, segment) end end |