Deepak
Deepak

Reputation: 73

HTML table not rendering properly

I have a Django view that sends a dictionary whose contents will be rendered in a html page.

My dictionary looks like this,

d ={ name : ['damon','stefan','elena'],
      age :  [200,200,25],
      address : ['mystic falls','mystic falls','mystic falls']
      supernatural : ['yes','yes','yes']}

Now my html table template looks like this,

<table class="table table-striped" border="1" class="dataframe">
    <thead>
     <tr style="text-align: center;">
       {% for i in d %}
       <th>{{ i }}</th>
       {% endfor %}
     </tr>
   </thead>
   <tbody>
     {% for i,j in d.items %}
      <tr style="text-align: center;">
       {% for x in j %}
        <td>{{ x }}</td>
       {% endfor %}
      </tr>
      {% endfor %}
   </tbody>
 </table>

problem:

When the rendering completes the dictionaries last values i.e ['yes','yes','yes'] are coming as a row. So below is how the output looks,

name     age       address    supernatural
damon    200    mystic falls  
stefan   200    mystic falls  
elena     25    mystic falls  
yes       yes   yes

Basically the last columns values are coming as rows.

Can you please help me why is this. Is there something wrong in my html table code above.

Upvotes: 0

Views: 1003

Answers (2)

Alexander
Alexander

Reputation: 90

I think you need to write the comma " , " after address:[]

Upvotes: 0

seuling
seuling

Reputation: 2956

Maybe you have to change your data type. your d is a little bit wierd type. I recommend you to change it to normal object (both can familiar in python / javascript object.) like below

    d2 = [
        {'name': 'damon', 'age': 200, 'address': 'mystic falls', 'sub': 'yes'},
        {'name': 'stefan', 'age': 200, 'address': 'mystic falls', 'sub': 'yes'},
        {'name': 'elena', 'age': 200, 'address': 'mystic falls', 'sub': 'yes'},
    ]

Then you can just forloop in template. like below.

<table class="table table-striped" border="1" class="dataframe">
    <thead>
     <tr style="text-align: center;">
       {% for k, v in d2.0.items %}
       <th>{{ k }}</th>
       {% endfor %}
     </tr>
   </thead>
   <tbody>
   {% for x in d2 %}
      <tr style="text-align: center;">
          <td>
              {{ x.name }}
          </td>
          <td>
              {{ x.age }}
          </td>
          <td>
              {{ x.address }}
          </td>
          <td>
              {{ x.sub }}
          </td>
      </tr>
  {% endfor %}
   </tbody>

ps. you can use your current data, but it's more complicated and really hard to understand - it's hard to matching one person to their data, and even it can't match when some field is blank.

Upvotes: 1

Related Questions