[mod_python] Nested For Loops

Erik Stephens mod_python at 24ksoftware.com
Mon Mar 8 10:39:07 EST 2004


On Mon, 8 Mar 2004, Robert Thomas Davis wrote:

> Hello all.  The following code is in a template file which gets
> passed the "record_set" variable, which is the result from an SQL
> query.  Its job is to create an table with the query information.
> This all works fine, however, I have been unable to figure out where
> to put the closing tag for the <tr> tag.  According to what I have
> read it should be placed after the end to the first inner loop.
> However, that places </tr> tags after every <td></td> pair.  This is
> all with the goal in mind of keeping things XHTML complient.  I
> would appreciate any comments and suggestions.

> <span>
> <table border="1">
> <caption><%= caption %></caption>
> <%
> for record in record_set:
>         # begin outer loop
> %>
>         <tr>
>         <%
>         for field in record:
>                 # begin inner loop
>         %>
>                 <td><%= field %></td>
>         <%
>         # end inner loop
>         %>
> <%
> # end outer loop
> %>
> </table>
> </span>

I got the following code to work like I think you want.  The position of
those '# end' comments or the whitespace around them affects the code, so
be careful with those.

  <table border=1>
<%
for i in range(10):
    # begin outer loop
%>
    <tr>
<%
    for j in range(5):
        # begin inner loop
%>
      <td><%= j %></td>
<%
    # end inner loop
%>
    </tr>
<%
# end outer loop
%>
  </table>


Personally, I find this difficult to read and very error-prone.  I'd
write it like this if possible.  Granted, this will probably get ugly
as the layout gets more complicated.

  <table border=1>
<%
for i in range(10):
    req.write('<tr>')
    for j in range(5):
        req.write('<td>[%d, %d]</td>' % (i,j))
    req.write('</tr>')

%>
  </table>


Best regards,
Erik


More information about the Mod_python mailing list