This page gives examples of how to use <al-for> to iterate over the different Python collection types and how to access the objects stored in the collection.

Each section contains Python code to create the data structure and an HTML template. Some examples show alternative ways of writing the template.

A list of strings

ctx.locals.strings = ['one', 'two', 'three', 'four', 'five']

<al-for iter="iter" expr="strings">
  <al-value expr="iter.value()" /><br />
</al-for>

A list of objects

class Person:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

people = [
    Person('Graham', 'Chapman'),
    Person('John', 'Cleese'),
    Person('Terry', 'Gilliam'),
    Person('Eric', 'Idle'),
    Person('Terry', 'Jones'),
    Person('Michael', 'Palin')]

ctx.locals.people = people

<al-for iter="iter" expr="people">
  <al-value expr="iter.value().last_name" />, <al-value expr="iter.value().first_name" /><br />
</al-for>

<al-for iter="iter" expr="people">
  <al-value expr="'%s, %s' % (iter.value().last_name, iter.value().first_name)" /><br />
</al-for>

A list of tuples

people = [
    ('Graham', 'Chapman'),
    ('John', 'Cleese'),
    ('Terry', 'Gilliam'),
    ('Eric', 'Idle'),
    ('Terry', 'Jones'),
    ('Michael', 'Palin')]

ctx.locals.people = people

<al-for iter="iter" expr="people">
  <al-value expr="iter.value()[1]" />, <al-value expr="iter.value()[0]" /><br />
</al-for>

<al-for iter="iter" expr="people">
  <al-exec expr="person = iter.value()" />
  <al-value expr="'%s, %s' % (person[1], person[0])" /><br />
</al-for>

A list of dictionaries

people = [
    {'first_name':'Graham', 'last_name':'Chapman'},
    {'first_name':'John', 'last_name':'Cleese'},
    {'first_name':'Terry', 'last_name':'Gilliam'},
    {'first_name':'Eric', 'last_name':'Idle'},
    {'first_name':'Terry', 'last_name':'Jones'},
    {'first_name':'Michael', 'last_name':'Palin'}]

ctx.locals.people = people

<al-for iter="iter" expr="people">
  <al-value expr="iter.value()['last_name']" />, <al-value expr="iter.value()['first_name']" /><br />
</al-for>

<al-for iter="iter" expr="people">
  <al-exec expr="person = iter.value()" />
  <al-value expr="'%s, %s' % (person['last_name'], person['first_name'])" /><br />
</al-for>

A dictionary

english_numbers = {1:'one', 2:'two', 3:'three', 4:'four', 5:'five'}
ctx.locals.number = english_numbers

<p>Keys:</p>
<al-for iter="iter" expr="numbers.keys()">
  <al-value expr="iter.value()" /><br />
</al-for>

<p>Values:</p>
<al-for iter="iter" expr="numbers.values()">
  <al-value expr="iter.value()" /><br />
</al-for>

<p>Keys and values:</p>
<al-for iter="iter" expr="numbers.items()">
  <al-value expr="iter.value()[0]" />: <al-value expr="iter.value()[1]" /><br />
</al-for>

None: Using_<al-for> (last edited 2011-02-15 06:05:18 by localhost)