Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use enumerate(zip(seq1,seq2)) in jinja2?

I'm trying to color some sequences of RNA using Django. I'm using enumerate and zip to find equals index in list. for example:

for i, (a, b) in enumerate(zip(seq1, seq2)):
        if a == b and i not in green:
            <p style="color: green;">{{i}}</p>

        elif a != b and i not in red:
            <p style="color: red;">{{i}}</p>

I recive this error in my template:

'for' statements should use the format 'for x in y': for i, (a, b) in enumerate(zip(seq1, seq2)):

like image 400
cacotsuki Avatar asked Oct 25 '25 04:10

cacotsuki


2 Answers

This code may help, try the code looks linke below, it works fine for me

(modified from some working code I've used)

when using 'for loop' in Jinja2, use loop.xxx to access some special vars

such as:
  loop.index        # index (1 inexed)
  loop.index0       # index (0 inexed)
  loop.revindex     # reversed ...
  loop.revindex0    # reversed ...
  loop.first        # True if first iteration
  loop.last         # True if last iteration
  loop.length
  loop.depth        # Recursive loop depth
  loop.depth0       # Recursive loop depth (0 inexed)

Code:

{% for (item_a, item_b) in zip(seq1, seq2) %}
{# important note: you may need to export __builtin__.zip to Jinja2 template engine first! I'm using htmlPy for my app GUI, I'm not sure it will or not affect the Jinja2 Enviroment, so you may need this #}
  <tr>
    <td>No.{{ loop.index0 }}</td>{# index (0 inexed) #}
    <td>No.{{ loop.index }}</td>{# index (1 started) #}
    <td>{{item_a}}</td>
    <td>{{item_b}}</td>
  </tr>
{% endfor %}

My Environment:

python 2.7.11 (I have py35 py36 but the code wasn't tested with them)

>py -2
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32
>pip2 show jinja2
Name: Jinja2
Version: 2.8
like image 119
返还击 Avatar answered Oct 27 '25 18:10

返还击


Django doesn't allow arbitrary code in for loop templates; you can't even loop over a simple range defined in the template. It's basically telling you you're only allowed to do simple for loops, reading one item per loop from a simple input iterable.

The solution is to make your "thing to iterate over" in the code that renders the template, and pass it in as part of the context, then iterate that.

like image 30
ShadowRanger Avatar answered Oct 27 '25 19:10

ShadowRanger