0

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?

1 Answer 1

1

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> 
Sign up to request clarification or add additional context in comments.

1 Comment

That's brilliant!! I didn't know there is a forloop counter available.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.