我正在尝试使用Django为某些RNA序列着色。我正在使用枚举和zip在列表中查找均等索引。例如:
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>
我在模板中收到此错误:
'for'语句应使用格式'for x in y':对于i,(a,b)在 枚举(zip(seq1,seq2)):
答案 0 :(得分:2)
Django doesn't allow arbitrary code in for loop templates; you can't even loop over a simple range
defined in the template。基本上是在告诉您只允许进行简单的for循环,从一个简单的可迭代输入中每个循环读取一项。
解决方案是在呈现模板的代码中使您的“迭代遍历”,并将其作为上下文的一部分传递,然后对其进行迭代。
答案 1 :(得分:0)
我认为 Jinja 模板引擎在这里解析i, (a, b)
循环中的for
部分时遇到了问题,因此也许值得为此提交工单。也许是故意的行为。
无论如何,您可以在此处用3元组压缩。首先要压缩,我们可以使用itertools.count
[python-doc]。因此,您将对'count'
的引用itertools.count()
传递给上下文,然后使用以下命令进行渲染:
{% for i, a, b in zip(indices(), seq1, seq2) %}
{# ... #}
{% endfor %}
例如:
>>> from jinja2 import Template
>>> from itertools import count
>>> Template('{% for i, a, b in zip(indices(), seq1, seq2) %} {{ (i, a, b) }}{% endfor %}').render(indices=count, seq1='foobar', seq2='babbaa', zip=zip)
" (0, 'f', 'b') (1, 'o', 'a') (2, 'o', 'b') (3, 'b', 'b') (4, 'a', 'a') (5, 'r', 'a')"
话虽如此,我强烈建议不在模板中编写业务逻辑。实际上,这就是Django模板引擎首先不允许这种语法的主要原因。最好在视图中创建zip
对象,然后将其通过上下文传递给渲染引擎。
答案 2 :(得分:0)
此代码可能会有所帮助,请尝试使用下面的代码链接,对我来说很好
(从我使用的一些工作代码中修改)
在Jinja2中使用“ for循环”时,请使用loop.xxx访问一些特殊的变量。
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)
{% 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 %}
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