Looping Over Data Passed to a Template
The example above shows how to display a single variable. What if you need to display the elements contained within a list? First, let’s take a look at our Hello World handler again and see how we build a data structure that can be looped or iterated over.
sub some_mode {
my $app = shift;
my $input = $app->{query}->param('some\_form_parameter');
my $plugin = plugin();
my $param = {};
my @people;
push @people, { person => 'David Byrne' };
push @people, { person => 'Harper Ford' };
$param->{people} = \@people;
my $tmpl = $plugin->load_tmpl('some_template.tmpl');
return $app->build_page( $tmpl, $param );
}
As the example above shows, a loop in Movable Type is nothing more than an array of hash references, or of name/value pairs. To loop over this data structure and display its contents, use the following template code:
<mt:setvarblock name="page_title">This is a page title</mt:setvarblock>
<mt:include name="include/header.tmpl">
<mt:loop name="people">
<p>Hello <mt:var name="person">!</p>
</mt:loop>
<mt:include name="include/footer.tmpl">
In the above example you will have noticed that we have added the <mt:loop>
tag. This tag takes as input the name of an array that was passed into the template as a parameter. Within the loop you can display the value of the elements contained within the array just like you do any other variable.
Loop Meta-Variables
To assist you in customizing the display of data within your loop, Movable Type manages for you a set of variables for you that can be used inside of a <mt:loop>
construct. These “meta-loop variables” are:
__first__
- returns true if the current element is the first element in the list.__last__
- returns true if the current element is the last element in the list.__index__
- returns the current index of the list being looped over (starting at 0)__counter__
- returns the number of times the current loop has been iterated over thus far (starting at 1)__odd__
- returns true if the current index is an odd number (e.g. 1, 3, 5, etc.)__even__
- returns true if the current index is an even number (e.g. 2, 4, 6, etc.)
For example, let’s use some of the above meta loop variables to create a properly formatted HTML list:
<mt:setvarblock name="page_title">This is a page title</mt:setvarblock>
<mt:include name="include/header.tmpl">
<mt:loop name="people">
<mt:if name="__first__"><ul></mt:if>
<li class="<mt:if name="__odd__">odd<mt:else>even</mt:if>">
<mt:var name="__counter__">. Hello <mt:var name="person">!
</li>
<mt:if name="__last__"></ul></mt:if>
</mt:loop>
<mt:include name="include/footer.tmpl">