A common problem is getting the <al-for> tag to do something sensible ;-).

The first thing to mention, which seems to be the big surprise for many, is that <al-for> does not behave like Python's for construct. Many people expect to be able to turn for person in people: print person into <al-for iter="person" expr="people"><al-value expr="person"/></al-for>. Sorry, but that does not work.

To iterate over a list of people the most basic form of the <al-for> tag would be:

  <al-for iter="people_iter" expr="people">
    ...
  </al-for>

The most important thing to understand is that the iter attribute is not the name of the current item from the list, it is the name of an iterator of type ListIterator. ListIterator provides a number of methods that describe the context of the loop. The most useful of those methods is value() which returns a reference to the current item from the list which, if you've needed to read this far, is probably what you were looking for.

So, the equivalent of:

for person in people:
    print person

is

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

Many people find people_iter.value() a little verbose when used more than once. A common way of making that a little more readable is to define another variable, person, using the <al-exec> tag.

<al-for iter="people_iter" expr="people">
  <al-exec expr="person = people_iter.value()" /> 
  <al-value expr="person" /><br />
</al-for>

Note that you can call the iterator whatever you want, I have used people_iter to make its purpose clear but it could equally be called iter or even i.

For further information refer to:

None: AlForTagIterator (last edited 2011-02-15 06:05:17 by localhost)