【问题标题】:Django Templates: how flexible are variables?Django 模板:变量有多灵活?
【发布时间】:2013-08-01 03:42:39
【问题描述】:

我需要在 teplate 中有一个变量,它基本上是 for 循环的计数器。问题是:我需要对其进行操作,这取决于我正在处理的 for 元素,我将不得不重置计数器(for 循环内的一个 IF)。

这在 Django 模板中可行吗?

这基本上是我想要的:

{% i = 0 %}
{% for l in list %}
    {% if i == 5 %}
        {% i = 0 %}
        Do Something
        <br>
    {% else %}
        {% i = i + 1 %}
    {% endif %}
{% endfor %}

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    你不能使用内置标签:

    http://www.mail-archive.com/django-users@googlegroups.com/msg27399.html

    以下 sn-ps 可能是一个很好的起点:

    编辑:为了记录,OP 需要一个带除法的条件。请参阅已接受的答案 here 以及此答案中的 cmets。

    【讨论】:

    • @averageman 如果您可以在模板渲染之前对视图中的可迭代对象进行排序会更容易。
    • 好吧,它已经排序了,但是我需要在 HTML 中每 5 个元素做一些事情(类似于
      每 5 个元素)。
    • @averageman 你可以用forloop.counter 'module' 5做一个条件。
    • 我可以在 Django 模板中做“counter modulo 5”吗?
    【解决方案2】:

    你想要的是 Django 的模板语言提供的 forloop.counter 变量。

    https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

    你会做这样的事情:

    {% for element in list %}
        {% if forloop.counter > 5 %}
            Do something
        {% else %}
            Do something else
        {% endif %}
    {% endfor %}
    

    如果你想循环地做某事,你基本上是在做一个模运算符(http://en.wikipedia.org/wiki/Modulo_operation),不幸的是,Django 模板没有这个,但它确实允许一个“除以”运算符。

    https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#divisibleby

    所以你会添加:

    {% if {{ forloop.counter|divisibleby:"5" }} %}
        {{ whatever }}
    {% endif %}
    

    【讨论】:

    • 重置计数器是什么意思?你到底想做什么?
    • 我不明白...在您的示例中,您从不使用 i 做任何事情。
    • @averageman 另外,这应该在后端而不是模板中完成。模板最好被认为是愚蠢的。
    猜你喜欢
    • 1970-01-01
    • 2014-04-13
    • 2020-07-23
    • 2012-12-11
    • 1970-01-01
    • 2010-11-01
    • 2016-03-21
    • 2018-11-17
    • 1970-01-01
    相关资源
    最近更新 更多