1

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?

NickP
  • 1,354
  • 1
  • 21
  • 51
  • Possible duplicate of [Django - How to do tuple unpacking in a template 'for' loop](http://stackoverflow.com/questions/271077/django-how-to-do-tuple-unpacking-in-a-template-for-loop) – shad0w_wa1k3r Mar 19 '17 at 16:44
  • Please post your urls.py and view function for corresponding template for more information. – Ajay Singh Mar 19 '17 at 16:44
  • @AjaySingh those aren't required. The question details are already sufficient. – shad0w_wa1k3r Mar 19 '17 at 16:45

1 Answers1

1

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 %}
arie
  • 18,737
  • 5
  • 70
  • 76