【问题标题】:How to check if for loop is in the middle value如何检查for循环是否在中间值
【发布时间】:2020-02-03 05:09:14
【问题描述】:

我无法在 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?

【问题讨论】:

  • value 是字典中的一个键,所以它的长度完全是错误的值。

标签: python html django


【解决方案1】:

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 值,我们也必须使用 add 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

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 2020-08-09
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多