简体   繁体   中英

Django HTML template table rendering

I want to render a table look like this:

<table>
  <tr>
    <td>some data</td>
    <th>special one</th>
    <td>some data</td>
      ...
    <td>some data</td>
  </tr>
  ...
</table>

There is a solution that can render all in the same tag.

<table>
  {% for rowval in results %}    
     <tr>
     {% for val in rowval %}
      <td>{{val}}</td>
     {% endfor %}
    </tr>
  {% endfor %}
</table> 

But in my case, there would be a th at the second place for every row of the data, if there is a record.

There is another solution that not as good as the answer below as it keeps partial table, td and tr in the view.

Is there a way to implement this feature?

There are some variables available inside a django template for loop , one of them is named forloop.counter which gives you the current iteration of the loop. You can use this variable to render something differently on the second loop

<table>
  {% for rowval in results %}    
    <tr>
      {% for val in rowval %}
        {% if forloop.counter == 2 %}
          <th>{{ val }}</th>
        {% else %}
          <td>{{ val }}</td>
        {% endif %}
     {% endfor %}
    </tr>
  {% endfor %}
</table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM