如何检查for循环是否在中间值

2024-05-16 23:02:11 发布

您现在位置:Python中文网/ 问答频道 /正文

在django模板中,我很难获得forloop中的中间循环。你知道吗

我试过用

{% for value in key.dictionary %}
    {% if forloop.counter == widthratio value|length 2 1 %}

但毫无效果。实际上在widthratio之后我得到了一个错误Expected %}

计算除法是从这篇文章Is there a filter for divide for Django Template?


Tags: djangokeyin模板fordictionaryifvalue
1条回答
网友
1楼 · 发布于 2024-05-16 23:02:11

widthratio不是一个过滤器,它是一个标签。但是可以使用aswidthratio的结果赋给变量:

{% widthratio key.dictionary|length 2 1 as midpoint %}
{% for key, value in key.dictionary.items %}
    {% if forloop.counter == midpoint|add:"0" %}

widthratio产生一个字符串,所以为了测试与整数forloop.counter值相等,我们也必须使用^{} filter as a work-aroundmidpoint转换回整数。你知道吗

请注意,我们采用字典的长度,而不是单个键的长度。在上面的示例中,我还选择循环字典项(键和值)。你知道吗

演示:

>>> from django.template import Context, Template
>>> t = Template("""\
... {% widthratio foo|length 2 1 as midpoint %}
... {% for key, value in foo.items %}
...     {% if forloop.counter = midpoint|add:"0" %}Half-way through!{% endif %}
...     {{ forloop.counter }}: {{ key }} == {{ value }}
... {% endfor %}
... """)
>>> context = Context({"foo": {"spam": 42, "vikings": 17, "eggs": 81}})
>>> print(t.render(context))



    1: spam == 42

    Half-way through!
    2: vikings == 17


    3: eggs == 81

相关问题 更多 >