0

I have multiple lists created in python. I am trying to convert these lists into HTML rows.

week = ['1','2']
date = ['2022-10-01','2022-10-09']

My HTML table should look like below:

Week     Date
1        2022-10-01
2        2022-10-09

what I tried so far:

{% for val in data %}
<tr>
  <td>
    {% for item in val.week %} {{ item }} <br> {% endfor %}
  </td>
  <td>
    {% for item in val.date %} {{ item }} <br> {% endfor %}
  </td>
</tr>
{% endfor %}

The problem with above code is every value is treated as cell instead of row and hence I am unable to apply any row related styles to the above.

Could someone help with how to convert these to rows instead of cells.

Thank you.

2
  • Will the length of both the lists be the same all the time? Commented Nov 1, 2022 at 9:20
  • Yes. Length would be same Commented Nov 1, 2022 at 9:21

2 Answers 2

1

You can use dictionary comprehension to convert the two lists into a dictionary where the key would be the week number and the value would be the corresponding date. You can loop over the dictionary as key and value using the items attribute in the template.

# views.py
week = [1, 2]
date = ['2022-10-01','2022-10-09']
data = {week[i]: date[i] for i in range(len(week))}
return render(request, 'template.html', {'data': data})


# template.html
{% for key, value in data.items %}
    <tr>
        <td> {{ key }} </td>
        <td> {{ value }} </td>
    </tr>
{% endfor %}
Sign up to request clarification or add additional context in comments.

Comments

1

try this approch...

------ views.py ------

week = ['1','2']
date = ['2022-10-01','2022-10-09']
data = tuple(zip(week,date))

------ html ------

<table style="border: 1px solid;  border-collapse: collapse;">
    <thead>
      <th>Weeks</th>
      <th>Dates</th>
    </thead>


    <tbody>
      <tbody>
        {% for i,j in data %}
        <tr>
          <td>{{i}}</td>
          <td>{{j}}</td>
        </tr>
        {% endfor %}
      </tbody>
    </tbody>

  </table>

-------- Output -------

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.