MortenSickel
MortenSickel

Reputation: 2200

How to get out some items from an array

In my flask / jinja2 app, I am getting some rows from a database to print in a table. For each row I want to define an identifier for the row from the first item, define the class of the row with the second item and print the rest of the row as table data. I am doing it like this, it works but feels a bit kludgy:

{%- for  item in row %}
    {% if loop.index==1 %}
      <tr id="rec{{item}}" 
    {% elif loop.index==2 %}
     class="{{item}}" >
    {% else %}
      <td>{{item}}</td>
    {% endif %}
  {% endfor -%}</tr>

I would like to do something like:

id="rec"+row.pop()
class=row.pop()

then use the variables id and class to define the row and afterwards iterate through what is left of the list. Is this possible in jinja2?

(Using jinja 2.8 as installed on debian 9, but may of course upgrade if that makes things better)

Upvotes: 0

Views: 231

Answers (2)

dustin-we
dustin-we

Reputation: 498

I think you can use slicing in Jinja templates, could you try this, since I can't test it atm:

    <tr id="rec{{row[0]}}" 
    class="{{row[1]}}" >
    {% for  item in row[2:] %}
      <td>{{item}}</td>
    {% endfor -%}
    </tr>

Upvotes: 1

D Malan
D Malan

Reputation: 11454

You could get the first items from the array using their indices and use a slice (e.g. row[2:]) of the array for the for-loop:

<tr id="rec{{row[0]}}" class="{{row[1]}}" >
{%- for item in row[2:] %}
   <td>{{item}}</td>
{% endfor -%}</tr>

Upvotes: 1

Related Questions