Iterate through a list in a CGI file and print out

2019-08-05 22:23发布

问题:

I have two list in a cgi file:

Numbers = [0, 1, 2, 3]

Letters = [A, B, C, D]

How do I iterate through these list and print the values out in html

I ideally my table would look like this:

0 A

1 B

2 C

3 D

and etc.

That means the tables and rows will have to be dictated by how long my list is and how many list I have. Thus I also would need to know how to iterate through the list and create the table in html script as I iterate through the list.

I have done this so far:

print'''
<html>
<head>
</head>
<body> 
<center>
<table border="0" cellspacing="15">
<tr>
<td align="center" style="font-size:1.25em;">
<p class="sansserif"> <b> Number: %d </b> <br>
Letter: %s </p>
</td>
</tr>
</table>
</center>
</body>
</html>'''%(Number, Letter)

But this is really not iterating through the list, I just know the list size and have done the necessary code for it. Also this just prints outs:

0

A

within a cell of a table

回答1:

There are two options

Using standard string formatting functions

Your attempt to create resulting content by % is going this direction.

However, as there are loops (rows in your output), and as neither % nor string.format support looping, you would have to create this "looping content" in your code and finally embed in resulting page.

bigtempl = '''<html>
<head>
</head>
<body> 
    <center>
        <table border="0" cellspacing="15">
        {rows}
        </table>
    </center>
    </body>
</html>'''

rowtempl = """
<tr>
    <td align="center" style="font-size:1.25em;">
    <p class="sansserif"> <b> Number: {number:d} </b> <br>
    Letter: {letter} </p>
    </td>
</tr>
"""

numbers = [0, 1, 2, 3]
letters = ["A", "B", "C", "D"]

lst = zip(numbers, letters)

rows = [rowtempl.format(number=number, letter=letter) for number, letter in lst]
rows = "".join(rows)

wholepage = bigtempl.format(rows=rows)

print wholepage

Using advanced template library

There are many packages, allowing to generate content based on templates and data structures. These often allow looping.

I once decided to keep using jinja2 and I am happy with that. Your task looks like this in Jinja2:

import jinja2

templ = '''<html>
<head>
</head>
<body> 
    <center>
        <table border="0" cellspacing="15">
        {% for number, letter in lst %}
            <tr>
                <td align="center" style="font-size:1.25em;">
                <p class="sansserif"> <b> Number: {{number}} </b> <br>
                Letter: {{letter}} </p>
                </td>
            </tr>
            {% endfor %}
        </table>
    </center>
    </body>
</html>'''

numbers = [0, 1, 2, 3]
letters = ["A", "B", "C", "D"]

lst = zip(numbers, letters)

template = jinja2.Template(templ)

print template.render(lst=lst)

Other templating solutions do that in very similar fashion.