This page last changed on May 29, 2012 by jed.wheeler@involver.com.

Overview

The for loop provides a simple tool to iterate through items in an array, whether that array is custom generated or originates with one of our SML Feature Blocks.


Caching Considerations

This tag has no caching considerations.


for loop attributes

Attribute Type Description
limit int lets you restrict how many items the loop will output
offset int lets you start the collection with the nth item
reversed boolean reverses the order of the items.
sort_by string Used to sort the most recent 300 or fewer items in the array.  Function is very similar to the Order attribute of the paginate helper block except it accepts more attributes, including rateing, and the order is always descending. Valid attributes are created_at, published_at, id, vote_count, rating, rating_count, fb_like_count, share_count.

Simple Example

{% for item in array %}
  {{ item }}
{% endfor%}

Simple example using a custom array with limit and offset

{% assign array = [1,2,3,4,5,6] %}
{% for item in array limit:2 offset:2 %}
  {{ item }}
{% endfor %}

results in:

3,4


Using the forloop Context Variable

You can use the special context variable forloop anywhere within a for loop to get information about the currently iterated item.

Attribute Type Description
forloop.length int length of the entire for loop
forloop.index int index of the current item
forloop.index0 int index of the current iteration (zero based)
forloop.rindex int how many items are still left?
forloop.rindex0 int how many items are still left?
forloop.first boolean is this the first iteration?
forloop.last boolean is this the last iteration?

Examples

Show horizontal rules under each element except for the last

{% for item in array%}
     {{ item }}

     {% unless forloop.last %}
       <hr />
     {% endunless %}
{% endfor%}

Using forloop position in if logic

You can use if logic inside your for loop to check which item in the list is currently being iterated and show different content for each position.

<ul>
{% for variable in array.feature_block %}
  <li>{{variable.title}}
  {% if forloop.index0 == 0 %}
	{% editable_image name:"style 1" %}
  {% elsif forloop.index0 == 1 %}
	{% editable_image name:"style 2" %}
  {% elsif forloop.index0 == 2 %}
	{% editable_image name:"style 3" %}
  {% elsif forloop.index0 == 3 %}
	{% editable_image name:"style 4" %}
  {% else %}
	Current position is {{forloop.index0}}
  {% endif %}</li>
{% endfor %}
</ul>

Ranges

Instead of looping over an existing collection, you can define a range of numbers to iterate through. The range can be defined by both literal and variable numbers:

For example, assuming item.quantity is 4:

{% for i in (1..item.quantity)%}
  {{ i }}
{% endfor%}

results in:

1,2,3,4


FAQ

There are currently no FAQ questions for this tag.

Document generated by Confluence on Feb 12, 2013 09:09