模板在使用with声明的变量中添加值

时间:2013-07-09 16:57:42

标签: django django-templates

有人可以解释一下为什么以下代码没有在current_count变量中添加值。我也在使用django 1.3版。以下代码给出了以下输出。

0

“图像”

10

“图像”

10

“图像”

。 。

“图像”表示显示实际图像。

我想要的是“只显示4张图片”。

{% with current_count=0 %}
    {% for row in people|slice:":4" %}
        {% if row %}
            {% for event in row %}
                {% if current_count < 4 %}
                    {{current_count}}
                    <div class="latest-photos-image-box">
                        <a href="{{ event.get_absolute_url }}"><img src="{{ event.mainthumb.url }}" alt="{{ event.title }}" /></a>
                    </div>
                {% endif %}
                {{ current_count|add:"1" }}
            {% endfor %}
        {% endif %}
    {% endfor %}
{% endwith %}

2 个答案:

答案 0 :(得分:0)

{% for event in row|slice:":4" %}

摆脱其余部分。

答案 1 :(得分:0)

这里的问题是{{ current_count|add:"1" }}执行添加但不存储任何内容。请改用循环计数器forloop.counter

但是,如果您需要一个无论嵌套级别如何都可以工作的计数器;这是一个配方(尚未测试,但应该工作):

>>> def monotonic():
...    count = 0
...    while True:
...       yield count
...       count += 1
... 
>>> counter = monotonic()
>>> # pass it to you request context dictionary

并在每次需要时使用{{ counter.next }}

请同时查看此问题:Flatten list of lists,您可能希望将人员行列表展平为更简单的人员列表,然后您可以将其切片。