MeL
MeL

Reputation: 1269

Display python list as table in html

I am struggling to format my list as a table in html (I am using django). Usually, I can easily achieve this by a for loop, like this:

<tbody>
    {% for item in lyrics %}
    <tr>
      <td>{{lyrics}}</td>
    </tr>
    {% endfor %}

But this gives me the whole list in every table cell.

If I do it like this...

  <tr>
      <td>{{lyrics.0}}</td>
      <td>{{lyrics.1}}</td>
    </tr>

...it works. But obviously I don't want to write it out for all n items.

I was hoping I can do something like...

{% for i in lyrics.i % }
     {{lyrics.i}}

But that didn't work either.

The following works in terms of getting the results neatly below each other, but obviously it's not a table:

<ol class='lyrics-list'>
          {{ lyrics|unordered_list }}
        </ol>

My list comes from my view:

lyrics = models.Song.objects.get().lyrics_as_list()

Upvotes: 0

Views: 3594

Answers (1)

captnsupremo
captnsupremo

Reputation: 730

It looks like when you specify for item in lyrics, you want to use item as your table cell element, rather than lyrics. That is, it seems like you want:

{% for item in lyrics %}
    <tr>
      <td>{{item}}</td>
    </tr>
{% endfor %}

Here's why: This for loop, creates a <td> element for every single element in lyrics. When you set the loop up, the identifier you used for each individual element is item. For each iteration of this loop, item contains a single element of lyrics.

Upvotes: 1

Related Questions