Home > Back-end >  Iterate and print elements for 2d arrays in Jinja syntax
Iterate and print elements for 2d arrays in Jinja syntax

Time:11-10

I want to iterate a 2d array to print every element in one cell each, how can I write this in jinja?

My code so far only prints each row (containing three elements) in a single cell:

Data: [[90,50,30],
       [40,20,70],
       [60,80,10]]

<div class="container">
  <table class="table">
      <thead>
          <th>No</th>
          <th>Value of Row 1</th>
          <th>Value of Row 2</th>
          <th>Value of Row 3</th>
      </thead>
      <tbody>
        {% for i in array %}
        <tr>
          <td>{{ loop.index }}</td>
          <td>{{ i }}</td>
          <td>{{ i }}</td>
          <td>{{ i }}</td>
        </tr>
        {% endfor %}
</div>

Expected output:

No Value of Row 1 Value of Row 2 Value of Row 3
1 90 50 30
2 40 20 70
3 60 80 10

CodePudding user response:

Change your template to:

<div class="container">
  <table class="table">
      <thead>
          <th>No</th>
          <th>Value of Row 1</th>
          <th>Value of Row 2</th>
          <th>Value of Row 3</th>
      </thead>
      <tbody>
        {% for row in data %}
        <tr>
        <td>{{ loop.index }}</td>
        {% for cell in row %}
          <td>{{ cell }}</td>
          {% endfor %}
        </tr>
        {% endfor %}
</div>
  • Related