Home > Back-end >  Adding values to cells in a specific column in HTML
Adding values to cells in a specific column in HTML

Time:01-06

I am creating a very basic table in HTML for my Django project. I got some help from Here to learn how to pass a list from my Django app to my HTML and generate rows for my values. My question this time is: how can I target the second, third, or any particular column for my list? For example, suppose I have a list of values and want to add all of them to Column 3 of my table. Here is the code I tried to use where i wanted to have {{ name }} values added to column two, but it keeps adding the cells to the first column


<html>
   <body>   
           <table border="1" cellpadding = "5" cellspacing="5"> 
               <tr>
                   <th> IDs </th>
                   <th> Names </th>
                   <th> Heights </th>
                 </tr>
               {% for id in myIDs %}
                   <tr> 
                      <td>{{ id }}</td>
                      
                   </tr>
               {% endfor %}
               <tr>
                   {% for name in myNames %}
                   <td>
                       <tr> 
                           <td>{{ name }}</td>      
                        </tr>
                   </td>    
                       {% endfor %}
               </tr>
               </table>           
   </body>
</html>

CodePudding user response:

For combining the data in tuples, you can use zip and for loop

Example:

MyIds = [1, 2, 3]
MyNames = [4, 5, 6]
MyHeights = [7, 8, 9]
data = []

for i, m, h in zip(MyIds, MyNames, MyHeights):
    data.append((i, m, h))

At the end, data will look like this -

 [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

I hope it helps

CodePudding user response:

For each id, name and height, create a tuple.

Then create a empty list and append the tuples to the data.

Then send the data as context

temp = (id, name, height)
data = []
data.append(temp)
return render(request, 'index.html', {data: data})

Now in the html page

{% for id, name, height in data %}
<tr>
    <td>{{id}}</td>
    <td>{{name}}</td>
    <td>{{height}}</td>
</tr>
{% endfor %}

  • Related