0

I have list of lists like this in django view:

res = [['Adam','334','Ford'],['Steve','130','Porsche'],['Dave','510','Ford']]

I want to display for example Adam, 334, Ford in table cells

{% for n in data %}

    {% for k in n %}

<table style="border:1px solid black;margin-top:15px;width:100%">

    <tr>

        <td style="width:33%;border:1px solid black;">
            {{ k.0 }}
        </td>

        <td style="width:33%;border:1px solid black">
            {{ k.1 }}
        </td>

        <td style="width:33%;border:1px solid black">
            {{ k.2 }}
        </td>
    </tr>
</table>
{% endfor %}

    {% endfor %}

Type of res is list and printing res[0][2] - gives Ford, but in table I get - k.0 = A k.1 = d k.2 = a With one for loop I get triple printing of res[0] in k.0/1/2

UPDATE

span = 3 # making list from every 3 elements

info = full_word.split("|") 

print_info = ["|".join(info[i:i + span]) for i in range(0, len(info), span)]

str_list = list(filter(None, print_info))

 res = []

        for el in str_list:
                sub = el.split('|')
                res.append(sub)

full_word - is a string like: Adam|334|ford|Steve|130|Porsche|Dave|510|Ford|

Type - list. Printing {{ n }} in html gives 3 lists separated by comma.

Victoria
  • 21
  • 1
  • 5

2 Answers2

2

This will help you

<table style="border:1px solid black;margin-top:15px;width:100%">
{% for n in data %}
    <tr>
    {% for k in n %}
        <td style="width:33%;border:1px solid black;">{{ k }}</td>
    {% endfor %}
    </tr>
{% endfor %}
</table>
Nj Nafir
  • 570
  • 3
  • 13
1

You can use this:

{% for n in data %}
    {% for first, second, third in n %}
        <td>{{ first }}</td>
        <td>{{ second }}</td>
        <td>{{ third }}</td>
    {% endfor %}
{% endfor %}
Pedram Parsian
  • 3,750
  • 3
  • 19
  • 34
  • **Need 3 values to unpack in for loop; got 9.** It counts every element of every list. I think it should work, but I'm missing something – Victoria Nov 27 '19 at 08:56
  • @Victoria I think the `res` is not holding what you expect it to, please include the code that's generating this `res` so that we can find out what's wrong. – Pedram Parsian Nov 27 '19 at 08:59
  • You either want `{% for element in n %} {{element}} {% endfor %}`, or no second for-loop and `{{n.0}}{{n.1}}...` The first handles sub-lists that vary in length, the second will "work" if the explicitly indexed elements do not exist by rendering a null string. – nigel222 Nov 27 '19 at 10:46