Reputation: 1414
I have recently tried to solve the challenge of handling a dynamic number of columns in my Django template (essentially working through a list containing lists that isnt standerdized).
I pass two things to my view:
test_array: an array that looks something like the following [[1,2,3],[1,2,3],[1,2,3]]
numbers: in this case 3 (indicating the number of attributes in the sub lists
I thought to solve this as follows:
<tbody>
{% for t in test_array %}
<tr>
{% for x in numbers %}
<td>{{ t.x }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
But the above returns no output. When I reference t.1, t.2 etc hardcoded this returns output.
As such, what is the best way to handle a dynamic number of columns in Django? Or, is there a more elegant way to solve the above?
Upvotes: 1
Views: 998
Reputation: 18972
Passing the length of the sublists to the the template isn't necessary.
As the list elements are also lists the inner loop could simply be reduced to this:
{% for x in t %}
<td>{{ x }}</td>
{% endfor %}
Upvotes: 1